diff --git "a/swe-bench-lite/pallets#flask#182ce3dd15dfa3537391c3efaf9c3ff407d134d4.graph.json" "b/swe-bench-lite/pallets#flask#182ce3dd15dfa3537391c3efaf9c3ff407d134d4.graph.json" new file mode 100644--- /dev/null +++ "b/swe-bench-lite/pallets#flask#182ce3dd15dfa3537391c3efaf9c3ff407d134d4.graph.json" @@ -0,0 +1 @@ +{"edges":[{"edgeType":"contains","source":992,"target":1026},{"edgeType":"calls","source":2228,"target":2182},{"edgeType":"contains","source":450,"target":651},{"edgeType":"calls","source":1919,"target":662},{"edgeType":"contains","source":1234,"target":2509},{"edgeType":"contains","source":960,"target":961},{"edgeType":"contains","source":119,"target":2720},{"edgeType":"calls","source":2588,"target":1328},{"edgeType":"calls","source":2659,"target":184},{"edgeType":"calls","source":2105,"target":710},{"edgeType":"calls","source":2818,"target":1333},{"edgeType":"contains","source":265,"target":1101},{"edgeType":"calls","source":2429,"target":2558},{"edgeType":"imports","source":427,"target":119},{"edgeType":"calls","source":1039,"target":194},{"edgeType":"calls","source":1380,"target":1779},{"edgeType":"contains","source":1222,"target":2353},{"edgeType":"calls","source":2495,"target":1569},{"edgeType":"calls","source":1558,"target":1546},{"edgeType":"calls","source":2642,"target":976},{"edgeType":"imports","source":1234,"target":1792},{"edgeType":"contains","source":1378,"target":160},{"edgeType":"contains","source":992,"target":1025},{"edgeType":"contains","source":1234,"target":2510},{"edgeType":"contains","source":450,"target":650},{"edgeType":"contains","source":283,"target":806},{"edgeType":"calls","source":2702,"target":1495},{"edgeType":"calls","source":2588,"target":1329},{"edgeType":"contains","source":119,"target":2719},{"edgeType":"contains","source":268,"target":1007},{"edgeType":"contains","source":121,"target":2393},{"edgeType":"contains","source":2,"target":4},{"edgeType":"contains","source":1668,"target":1741},{"edgeType":"imports","source":1447,"target":739},{"edgeType":"contains","source":1670,"target":1679},{"edgeType":"calls","source":1380,"target":1778},{"edgeType":"calls","source":2010,"target":1539},{"edgeType":"contains","source":165,"target":236},{"edgeType":"calls","source":1278,"target":976},{"edgeType":"calls","source":2588,"target":1330},{"edgeType":"calls","source":2659,"target":186},{"edgeType":"contains","source":2877,"target":465},{"edgeType":"calls","source":2105,"target":976},{"edgeType":"contains","source":450,"target":653},{"edgeType":"calls","source":665,"target":1220},{"edgeType":"calls","source":1850,"target":689},{"edgeType":"calls","source":2623,"target":1298},{"edgeType":"contains","source":1234,"target":2507},{"edgeType":"calls","source":2677,"target":681},{"edgeType":"calls","source":2105,"target":708},{"edgeType":"contains","source":121,"target":2396},{"edgeType":"calls","source":2818,"target":1331},{"edgeType":"calls","source":2200,"target":670},{"edgeType":"contains","source":126,"target":127},{"edgeType":"calls","source":1952,"target":1226},{"edgeType":"calls","source":2224,"target":1776},{"edgeType":"calls","source":2173,"target":186},{"edgeType":"contains","source":1897,"target":2038},{"edgeType":"calls","source":2319,"target":681},{"edgeType":"calls","source":2332,"target":2392},{"edgeType":"calls","source":2880,"target":2052},{"edgeType":"contains","source":1794,"target":2060},{"edgeType":"contains","source":1,"target":302},{"edgeType":"contains","source":992,"target":1027},{"edgeType":"contains","source":430,"target":1272},{"edgeType":"contains","source":450,"target":652},{"edgeType":"contains","source":283,"target":808},{"edgeType":"calls","source":2588,"target":1327},{"edgeType":"contains","source":119,"target":2721},{"edgeType":"contains","source":1234,"target":2508},{"edgeType":"calls","source":2818,"target":1332},{"edgeType":"calls","source":2152,"target":2159},{"edgeType":"calls","source":1048,"target":974},{"edgeType":"calls","source":1952,"target":1225},{"edgeType":"calls","source":2173,"target":187},{"edgeType":"calls","source":1782,"target":681},{"edgeType":"contains","source":1234,"target":2513},{"edgeType":"contains","source":40,"target":152},{"edgeType":"contains","source":119,"target":2724},{"edgeType":"calls","source":1159,"target":170},{"edgeType":"calls","source":1952,"target":2013},{"edgeType":"contains","source":450,"target":655},{"edgeType":"calls","source":2818,"target":1329},{"edgeType":"contains","source":430,"target":2068},{"edgeType":"calls","source":1525,"target":451},{"edgeType":"contains","source":60,"target":61},{"edgeType":"calls","source":954,"target":976},{"edgeType":"calls","source":1171,"target":326},{"edgeType":"contains","source":2075,"target":2076},{"edgeType":"calls","source":1269,"target":195},{"edgeType":"contains","source":1,"target":40},{"edgeType":"calls","source":2224,"target":1774},{"edgeType":"calls","source":2309,"target":2310},{"edgeType":"calls","source":2173,"target":184},{"edgeType":"contains","source":160,"target":660},{"edgeType":"contains","source":283,"target":811},{"edgeType":"contains","source":1234,"target":2514},{"edgeType":"calls","source":1535,"target":669},{"edgeType":"calls","source":1299,"target":1907},{"edgeType":"contains","source":119,"target":2723},{"edgeType":"contains","source":450,"target":654},{"edgeType":"contains","source":121,"target":2397},{"edgeType":"contains","source":427,"target":2160},{"edgeType":"contains","source":1794,"target":2331},{"edgeType":"calls","source":2818,"target":1330},{"edgeType":"calls","source":2676,"target":976},{"edgeType":"calls","source":674,"target":670},{"edgeType":"calls","source":1782,"target":675},{"edgeType":"contains","source":1670,"target":1683},{"edgeType":"calls","source":2648,"target":2108},{"edgeType":"calls","source":2083,"target":1918},{"edgeType":"contains","source":11,"target":1050},{"edgeType":"calls","source":1968,"target":194},{"edgeType":"contains","source":1234,"target":2515},{"edgeType":"calls","source":2880,"target":2051},{"edgeType":"contains","source":1045,"target":1239},{"edgeType":"contains","source":1234,"target":2511},{"edgeType":"calls","source":2818,"target":1327},{"edgeType":"calls","source":1062,"target":1065},{"edgeType":"calls","source":1024,"target":1186},{"edgeType":"contains","source":450,"target":657},{"edgeType":"contains","source":116,"target":969},{"edgeType":"contains","source":121,"target":2400},{"edgeType":"calls","source":1952,"target":958},{"edgeType":"calls","source":2368,"target":1536},{"edgeType":"contains","source":1668,"target":1742},{"edgeType":"contains","source":306,"target":364},{"edgeType":"contains","source":1472,"target":1476},{"edgeType":"contains","source":283,"target":813},{"edgeType":"calls","source":1380,"target":1777},{"edgeType":"calls","source":1782,"target":678},{"edgeType":"calls","source":1812,"target":1862},{"edgeType":"contains","source":119,"target":2725},{"edgeType":"contains","source":1234,"target":2512},{"edgeType":"contains","source":1051,"target":1052},{"edgeType":"contains","source":450,"target":656},{"edgeType":"calls","source":2838,"target":2558},{"edgeType":"calls","source":1952,"target":2014},{"edgeType":"contains","source":17,"target":73},{"edgeType":"contains","source":1111,"target":1570},{"edgeType":"contains","source":57,"target":947},{"edgeType":"calls","source":2677,"target":678},{"edgeType":"calls","source":2818,"target":1328},{"edgeType":"calls","source":2541,"target":666},{"edgeType":"calls","source":1994,"target":976},{"edgeType":"contains","source":180,"target":1362},{"edgeType":"imports","source":293,"target":304},{"edgeType":"calls","source":1269,"target":196},{"edgeType":"calls","source":2258,"target":1776},{"edgeType":"imports","source":135,"target":446},{"edgeType":"contains","source":119,"target":1932},{"edgeType":"calls","source":1516,"target":1524},{"edgeType":"calls","source":2319,"target":678},{"edgeType":"contains","source":1178,"target":1082},{"edgeType":"contains","source":513,"target":556},{"edgeType":"contains","source":121,"target":2402},{"edgeType":"calls","source":2263,"target":296},{"edgeType":"calls","source":2258,"target":1244},{"edgeType":"calls","source":2490,"target":1187},{"edgeType":"calls","source":2878,"target":1843},{"edgeType":"calls","source":979,"target":196},{"edgeType":"calls","source":2021,"target":1191},{"edgeType":"contains","source":2488,"target":2490},{"edgeType":"calls","source":2677,"target":675},{"edgeType":"contains","source":306,"target":366},{"edgeType":"imports","source":1447,"target":2334},{"edgeType":"calls","source":2085,"target":528},{"edgeType":"calls","source":2248,"target":2083},{"edgeType":"contains","source":283,"target":815},{"edgeType":"contains","source":450,"target":659},{"edgeType":"contains","source":1234,"target":2518},{"edgeType":"calls","source":2319,"target":675},{"edgeType":"calls","source":118,"target":196},{"edgeType":"contains","source":88,"target":1838},{"edgeType":"calls","source":442,"target":194},{"edgeType":"calls","source":979,"target":195},{"edgeType":"contains","source":113,"target":270},{"edgeType":"contains","source":119,"target":2199},{"edgeType":"contains","source":2488,"target":2491},{"edgeType":"contains","source":65,"target":966},{"edgeType":"imports","source":1113,"target":1853},{"edgeType":"calls","source":1888,"target":556},{"edgeType":"contains","source":1,"target":43},{"edgeType":"contains","source":1234,"target":2519},{"edgeType":"contains","source":450,"target":658},{"edgeType":"calls","source":2258,"target":1774},{"edgeType":"calls","source":1240,"target":1089},{"edgeType":"contains","source":1178,"target":1084},{"edgeType":"contains","source":513,"target":558},{"edgeType":"calls","source":2265,"target":1289},{"edgeType":"contains","source":88,"target":1841},{"edgeType":"calls","source":2154,"target":502},{"edgeType":"contains","source":11,"target":264},{"edgeType":"contains","source":1670,"target":1684},{"edgeType":"calls","source":2327,"target":689},{"edgeType":"contains","source":283,"target":817},{"edgeType":"calls","source":1360,"target":1336},{"edgeType":"contains","source":1,"target":1103},{"edgeType":"contains","source":1234,"target":2516},{"edgeType":"contains","source":1,"target":46},{"edgeType":"contains","source":1178,"target":1083},{"edgeType":"calls","source":1900,"target":451},{"edgeType":"imports","source":980,"target":425},{"edgeType":"calls","source":1380,"target":451},{"edgeType":"contains","source":121,"target":2403},{"edgeType":"calls","source":1509,"target":680},{"edgeType":"contains","source":513,"target":557},{"edgeType":"calls","source":2265,"target":1290},{"edgeType":"contains","source":88,"target":1840},{"edgeType":"contains","source":1482,"target":1435},{"edgeType":"contains","source":2488,"target":2489},{"edgeType":"calls","source":1312,"target":1237},{"edgeType":"contains","source":1234,"target":2517},{"edgeType":"calls","source":2363,"target":1688},{"edgeType":"contains","source":1794,"target":1805},{"edgeType":"calls","source":2702,"target":1485},{"edgeType":"contains","source":1178,"target":1086},{"edgeType":"contains","source":513,"target":560},{"edgeType":"contains","source":1794,"target":1810},{"edgeType":"calls","source":1535,"target":662},{"edgeType":"contains","source":306,"target":371},{"edgeType":"contains","source":1439,"target":1452},{"edgeType":"contains","source":57,"target":955},{"edgeType":"contains","source":283,"target":819},{"edgeType":"contains","source":298,"target":354},{"edgeType":"contains","source":1234,"target":2522},{"edgeType":"calls","source":1874,"target":194},{"edgeType":"contains","source":25,"target":97},{"edgeType":"calls","source":1107,"target":1245},{"edgeType":"calls","source":2098,"target":1708},{"edgeType":"calls","source":1240,"target":1086},{"edgeType":"calls","source":1269,"target":187},{"edgeType":"contains","source":1109,"target":1110},{"edgeType":"contains","source":135,"target":121},{"edgeType":"calls","source":1240,"target":1085},{"edgeType":"contains","source":1178,"target":1085},{"edgeType":"calls","source":2083,"target":1909},{"edgeType":"calls","source":1269,"target":186},{"edgeType":"calls","source":1798,"target":700},{"edgeType":"contains","source":513,"target":559},{"edgeType":"calls","source":1533,"target":194},{"edgeType":"calls","source":1354,"target":194},{"edgeType":"contains","source":88,"target":1842},{"edgeType":"contains","source":293,"target":1830},{"edgeType":"contains","source":298,"target":1675},{"edgeType":"contains","source":1868,"target":1895},{"edgeType":"contains","source":306,"target":369},{"edgeType":"contains","source":1439,"target":1453},{"edgeType":"calls","source":1821,"target":515},{"edgeType":"calls","source":1627,"target":451},{"edgeType":"contains","source":1794,"target":2340},{"edgeType":"contains","source":1234,"target":2523},{"edgeType":"calls","source":1506,"target":502},{"edgeType":"calls","source":2098,"target":1709},{"edgeType":"calls","source":1243,"target":1256},{"edgeType":"calls","source":2796,"target":2797},{"edgeType":"contains","source":1794,"target":2072},{"edgeType":"contains","source":1,"target":50},{"edgeType":"contains","source":1178,"target":1088},{"edgeType":"contains","source":2488,"target":2492},{"edgeType":"calls","source":2659,"target":170},{"edgeType":"calls","source":118,"target":195},{"edgeType":"contains","source":1222,"target":2363},{"edgeType":"calls","source":2812,"target":976},{"edgeType":"contains","source":2645,"target":2646},{"edgeType":"calls","source":2331,"target":296},{"edgeType":"calls","source":1900,"target":976},{"edgeType":"contains","source":306,"target":373},{"edgeType":"calls","source":1320,"target":194},{"edgeType":"contains","source":19,"target":21},{"edgeType":"contains","source":283,"target":821},{"edgeType":"contains","source":57,"target":957},{"edgeType":"calls","source":1678,"target":194},{"edgeType":"contains","source":1234,"target":2520},{"edgeType":"contains","source":513,"target":562},{"edgeType":"contains","source":126,"target":139},{"edgeType":"calls","source":1685,"target":1827},{"edgeType":"calls","source":1240,"target":1088},{"edgeType":"imports","source":1234,"target":739},{"edgeType":"contains","source":1178,"target":1087},{"edgeType":"imports","source":1854,"target":1865},{"edgeType":"calls","source":2154,"target":499},{"edgeType":"contains","source":57,"target":956},{"edgeType":"contains","source":19,"target":20},{"edgeType":"calls","source":2096,"target":976},{"edgeType":"calls","source":1032,"target":664},{"edgeType":"contains","source":1234,"target":2521},{"edgeType":"contains","source":513,"target":561},{"edgeType":"calls","source":1952,"target":948},{"edgeType":"calls","source":1240,"target":1087},{"edgeType":"contains","source":1,"target":19},{"edgeType":"contains","source":346,"target":423},{"edgeType":"contains","source":1501,"target":1879},{"edgeType":"contains","source":352,"target":2351},{"edgeType":"calls","source":1408,"target":664},{"edgeType":"imports","source":1447,"target":459},{"edgeType":"contains","source":352,"target":2087},{"edgeType":"calls","source":1633,"target":1088},{"edgeType":"calls","source":1899,"target":241},{"edgeType":"calls","source":2818,"target":1086},{"edgeType":"contains","source":450,"target":634},{"edgeType":"contains","source":1273,"target":1284},{"edgeType":"contains","source":1111,"target":1548},{"edgeType":"contains","source":1078,"target":2571},{"edgeType":"calls","source":2167,"target":1976},{"edgeType":"contains","source":119,"target":2703},{"edgeType":"contains","source":223,"target":272},{"edgeType":"contains","source":121,"target":2376},{"edgeType":"contains","source":346,"target":422},{"edgeType":"imports","source":1447,"target":458},{"edgeType":"calls","source":2395,"target":194},{"edgeType":"contains","source":352,"target":2086},{"edgeType":"contains","source":1447,"target":119},{"edgeType":"calls","source":1633,"target":1087},{"edgeType":"calls","source":2600,"target":710},{"edgeType":"calls","source":2363,"target":1979},{"edgeType":"calls","source":2818,"target":1087},{"edgeType":"calls","source":2167,"target":1977},{"edgeType":"contains","source":438,"target":1269},{"edgeType":"calls","source":1909,"target":194},{"edgeType":"contains","source":283,"target":789},{"edgeType":"contains","source":282,"target":820},{"edgeType":"calls","source":2796,"target":976},{"edgeType":"contains","source":450,"target":633},{"edgeType":"imports","source":1234,"target":1248},{"edgeType":"contains","source":202,"target":1718},{"edgeType":"calls","source":2627,"target":662},{"edgeType":"imports","source":76,"target":147},{"edgeType":"calls","source":2448,"target":662},{"edgeType":"contains","source":293,"target":1804},{"edgeType":"contains","source":1836,"target":1798},{"edgeType":"contains","source":1031,"target":1652},{"edgeType":"contains","source":1392,"target":1821},{"edgeType":"calls","source":2818,"target":1084},{"edgeType":"contains","source":450,"target":636},{"edgeType":"contains","source":283,"target":792},{"edgeType":"calls","source":2429,"target":194},{"edgeType":"calls","source":2359,"target":2364},{"edgeType":"contains","source":119,"target":2705},{"edgeType":"calls","source":1596,"target":1708},{"edgeType":"calls","source":2363,"target":1976},{"edgeType":"contains","source":121,"target":2379},{"edgeType":"calls","source":665,"target":707},{"edgeType":"contains","source":465,"target":699},{"edgeType":"calls","source":112,"target":673},{"edgeType":"calls","source":1534,"target":194},{"edgeType":"calls","source":1095,"target":326},{"edgeType":"calls","source":2651,"target":976},{"edgeType":"calls","source":1749,"target":664},{"edgeType":"calls","source":2354,"target":670},{"edgeType":"calls","source":1633,"target":1089},{"edgeType":"contains","source":96,"target":1568},{"edgeType":"calls","source":2818,"target":1085},{"edgeType":"contains","source":283,"target":791},{"edgeType":"contains","source":282,"target":822},{"edgeType":"contains","source":450,"target":635},{"edgeType":"calls","source":2363,"target":1977},{"edgeType":"calls","source":2167,"target":1975},{"edgeType":"contains","source":119,"target":2704},{"edgeType":"calls","source":1299,"target":1401},{"edgeType":"contains","source":1794,"target":2573},{"edgeType":"calls","source":2600,"target":708},{"edgeType":"calls","source":461,"target":425},{"edgeType":"calls","source":256,"target":432},{"edgeType":"contains","source":119,"target":2179},{"edgeType":"calls","source":2085,"target":2135},{"edgeType":"calls","source":1633,"target":1084},{"edgeType":"contains","source":844,"target":845},{"edgeType":"contains","source":465,"target":702},{"edgeType":"contains","source":60,"target":308},{"edgeType":"calls","source":1909,"target":2041},{"edgeType":"contains","source":282,"target":826},{"edgeType":"contains","source":1234,"target":2497},{"edgeType":"contains","source":283,"target":794},{"edgeType":"contains","source":119,"target":2707},{"edgeType":"calls","source":2548,"target":2581},{"edgeType":"calls","source":1159,"target":186},{"edgeType":"calls","source":665,"target":1231},{"edgeType":"calls","source":1252,"target":1267},{"edgeType":"contains","source":1392,"target":1563},{"edgeType":"calls","source":2818,"target":1082},{"edgeType":"contains","source":450,"target":638},{"edgeType":"calls","source":2322,"target":2188},{"edgeType":"calls","source":1824,"target":976},{"edgeType":"calls","source":1091,"target":973},{"edgeType":"contains","source":1472,"target":1990},{"edgeType":"contains","source":121,"target":2381},{"edgeType":"imports","source":307,"target":119},{"edgeType":"calls","source":1263,"target":662},{"edgeType":"calls","source":1952,"target":1236},{"edgeType":"contains","source":1094,"target":2343},{"edgeType":"contains","source":131,"target":1013},{"edgeType":"calls","source":1633,"target":1083},{"edgeType":"contains","source":202,"target":1719},{"edgeType":"contains","source":1668,"target":1728},{"edgeType":"contains","source":1794,"target":2579},{"edgeType":"contains","source":465,"target":701},{"edgeType":"calls","source":2642,"target":1253},{"edgeType":"contains","source":1721,"target":1935},{"edgeType":"contains","source":1234,"target":2498},{"edgeType":"contains","source":282,"target":824},{"edgeType":"contains","source":450,"target":637},{"edgeType":"contains","source":81,"target":978},{"edgeType":"contains","source":67,"target":355},{"edgeType":"contains","source":1392,"target":1564},{"edgeType":"contains","source":119,"target":2706},{"edgeType":"calls","source":1252,"target":1266},{"edgeType":"calls","source":2818,"target":1083},{"edgeType":"calls","source":1952,"target":971},{"edgeType":"calls","source":1506,"target":1320},{"edgeType":"contains","source":305,"target":904},{"edgeType":"calls","source":2489,"target":976},{"edgeType":"contains","source":121,"target":2380},{"edgeType":"calls","source":1952,"target":1235},{"edgeType":"calls","source":2363,"target":1975},{"edgeType":"calls","source":1633,"target":1086},{"edgeType":"contains","source":1034,"target":1035},{"edgeType":"contains","source":465,"target":704},{"edgeType":"calls","source":2309,"target":2324},{"edgeType":"contains","source":844,"target":847},{"edgeType":"contains","source":293,"target":1808},{"edgeType":"contains","source":1,"target":25},{"edgeType":"contains","source":60,"target":310},{"edgeType":"calls","source":1483,"target":451},{"edgeType":"contains","source":282,"target":828},{"edgeType":"contains","source":131,"target":1280},{"edgeType":"contains","source":2446,"target":2448},{"edgeType":"contains","source":119,"target":2709},{"edgeType":"calls","source":1671,"target":436},{"edgeType":"contains","source":1273,"target":1286},{"edgeType":"calls","source":2659,"target":195},{"edgeType":"calls","source":2107,"target":1980},{"edgeType":"contains","source":450,"target":640},{"edgeType":"contains","source":1794,"target":2576},{"edgeType":"calls","source":1846,"target":296},{"edgeType":"calls","source":1269,"target":1270},{"edgeType":"calls","source":1633,"target":1085},{"edgeType":"calls","source":1500,"target":1244},{"edgeType":"contains","source":1031,"target":1127},{"edgeType":"contains","source":465,"target":703},{"edgeType":"contains","source":844,"target":846},{"edgeType":"imports","source":135,"target":429},{"edgeType":"calls","source":2536,"target":1102},{"edgeType":"contains","source":1721,"target":1933},{"edgeType":"contains","source":283,"target":796},{"edgeType":"calls","source":1817,"target":666},{"edgeType":"contains","source":43,"target":44},{"edgeType":"calls","source":1159,"target":187},{"edgeType":"contains","source":1234,"target":2496},{"edgeType":"contains","source":119,"target":2708},{"edgeType":"calls","source":2659,"target":196},{"edgeType":"calls","source":2107,"target":1981},{"edgeType":"calls","source":1952,"target":973},{"edgeType":"calls","source":1252,"target":1268},{"edgeType":"contains","source":450,"target":639},{"edgeType":"contains","source":1868,"target":1869},{"edgeType":"contains","source":11,"target":1300},{"edgeType":"calls","source":1845,"target":326},{"edgeType":"contains","source":1794,"target":2577},{"edgeType":"calls","source":1730,"target":1244},{"edgeType":"contains","source":1794,"target":2582},{"edgeType":"calls","source":1517,"target":976},{"edgeType":"contains","source":2727,"target":2728},{"edgeType":"contains","source":450,"target":643},{"edgeType":"contains","source":1234,"target":2501},{"edgeType":"calls","source":2702,"target":1502},{"edgeType":"contains","source":1758,"target":1848},{"edgeType":"contains","source":119,"target":2712},{"edgeType":"calls","source":2173,"target":196},{"edgeType":"contains","source":131,"target":1282},{"edgeType":"contains","source":131,"target":1283},{"edgeType":"contains","source":1836,"target":1809},{"edgeType":"contains","source":1411,"target":1771},{"edgeType":"contains","source":87,"target":1854},{"edgeType":"contains","source":1501,"target":1888},{"edgeType":"contains","source":980,"target":2446},{"edgeType":"contains","source":180,"target":1349},{"edgeType":"contains","source":844,"target":848},{"edgeType":"contains","source":1794,"target":2583},{"edgeType":"contains","source":446,"target":1030},{"edgeType":"calls","source":2838,"target":194},{"edgeType":"calls","source":1919,"target":669},{"edgeType":"contains","source":1273,"target":1293},{"edgeType":"calls","source":1380,"target":1787},{"edgeType":"contains","source":1234,"target":2502},{"edgeType":"contains","source":2727,"target":2729},{"edgeType":"contains","source":450,"target":642},{"edgeType":"contains","source":283,"target":798},{"edgeType":"calls","source":2640,"target":2368},{"edgeType":"contains","source":131,"target":1281},{"edgeType":"contains","source":119,"target":2711},{"edgeType":"contains","source":2471,"target":2473},{"edgeType":"contains","source":119,"target":2710},{"edgeType":"calls","source":1488,"target":1345},{"edgeType":"contains","source":450,"target":641},{"edgeType":"calls","source":2107,"target":1979},{"edgeType":"contains","source":121,"target":2384},{"edgeType":"contains","source":465,"target":705},{"edgeType":"contains","source":180,"target":1348},{"edgeType":"contains","source":2000,"target":2011},{"edgeType":"calls","source":2541,"target":681},{"edgeType":"contains","source":1668,"target":1729},{"edgeType":"calls","source":951,"target":290},{"edgeType":"calls","source":1633,"target":1082},{"edgeType":"contains","source":1794,"target":2580},{"edgeType":"contains","source":450,"target":645},{"edgeType":"contains","source":119,"target":2714},{"edgeType":"contains","source":1234,"target":2499},{"edgeType":"calls","source":2677,"target":690},{"edgeType":"contains","source":1392,"target":1565},{"edgeType":"contains","source":121,"target":2387},{"edgeType":"imports","source":1234,"target":1782},{"edgeType":"calls","source":1159,"target":184},{"edgeType":"calls","source":2107,"target":1976},{"edgeType":"calls","source":2085,"target":1601},{"edgeType":"calls","source":2541,"target":678},{"edgeType":"imports","source":135,"target":1762},{"edgeType":"contains","source":180,"target":1351},{"edgeType":"calls","source":1091,"target":971},{"edgeType":"calls","source":2297,"target":1900},{"edgeType":"calls","source":1782,"target":690},{"edgeType":"contains","source":450,"target":644},{"edgeType":"contains","source":282,"target":831},{"edgeType":"contains","source":283,"target":800},{"edgeType":"calls","source":2429,"target":451},{"edgeType":"calls","source":857,"target":296},{"edgeType":"contains","source":119,"target":2713},{"edgeType":"contains","source":1234,"target":2500},{"edgeType":"contains","source":1758,"target":1847},{"edgeType":"imports","source":1447,"target":1257},{"edgeType":"calls","source":2173,"target":195},{"edgeType":"contains","source":2058,"target":2061},{"edgeType":"calls","source":2319,"target":690},{"edgeType":"contains","source":1472,"target":1993},{"edgeType":"calls","source":118,"target":215},{"edgeType":"contains","source":121,"target":2386},{"edgeType":"contains","source":2091,"target":2095},{"edgeType":"contains","source":135,"target":1952},{"edgeType":"calls","source":2107,"target":1977},{"edgeType":"calls","source":2085,"target":1602},{"edgeType":"contains","source":1513,"target":1515},{"edgeType":"calls","source":2813,"target":2817},{"edgeType":"calls","source":2702,"target":1498},{"edgeType":"calls","source":2059,"target":290},{"edgeType":"contains","source":113,"target":259},{"edgeType":"calls","source":1159,"target":971},{"edgeType":"calls","source":2059,"target":2140},{"edgeType":"contains","source":25,"target":80},{"edgeType":"calls","source":1900,"target":1255},{"edgeType":"contains","source":1234,"target":2505},{"edgeType":"contains","source":2471,"target":2476},{"edgeType":"contains","source":119,"target":2716},{"edgeType":"contains","source":2727,"target":2732},{"edgeType":"contains","source":457,"target":430},{"edgeType":"contains","source":450,"target":647},{"edgeType":"contains","source":1794,"target":2586},{"edgeType":"contains","source":65,"target":162},{"edgeType":"calls","source":1952,"target":1228},{"edgeType":"contains","source":1411,"target":1511},{"edgeType":"contains","source":180,"target":1353},{"edgeType":"calls","source":2588,"target":1333},{"edgeType":"contains","source":1668,"target":1736},{"edgeType":"contains","source":992,"target":1021},{"edgeType":"calls","source":2813,"target":2814},{"edgeType":"calls","source":2702,"target":1499},{"edgeType":"contains","source":1794,"target":2323},{"edgeType":"contains","source":1234,"target":2506},{"edgeType":"calls","source":134,"target":241},{"edgeType":"contains","source":282,"target":833},{"edgeType":"contains","source":283,"target":802},{"edgeType":"contains","source":119,"target":2715},{"edgeType":"contains","source":2471,"target":2477},{"edgeType":"calls","source":2226,"target":664},{"edgeType":"contains","source":450,"target":646},{"edgeType":"calls","source":1474,"target":1247},{"edgeType":"calls","source":2318,"target":1776},{"edgeType":"contains","source":101,"target":102},{"edgeType":"contains","source":165,"target":232},{"edgeType":"contains","source":5,"target":171},{"edgeType":"contains","source":121,"target":2388},{"edgeType":"calls","source":1952,"target":1227},{"edgeType":"contains","source":430,"target":2058},{"edgeType":"calls","source":2813,"target":2815},{"edgeType":"calls","source":2107,"target":1975},{"edgeType":"imports","source":1836,"target":295},{"edgeType":"calls","source":2791,"target":326},{"edgeType":"contains","source":992,"target":1020},{"edgeType":"calls","source":2702,"target":1496},{"edgeType":"calls","source":2323,"target":296},{"edgeType":"calls","source":1926,"target":451},{"edgeType":"calls","source":1312,"target":194},{"edgeType":"contains","source":1234,"target":2503},{"edgeType":"imports","source":1447,"target":461},{"edgeType":"contains","source":463,"target":1039},{"edgeType":"contains","source":1758,"target":1850},{"edgeType":"contains","source":450,"target":649},{"edgeType":"calls","source":2367,"target":2368},{"edgeType":"contains","source":121,"target":2391},{"edgeType":"calls","source":1833,"target":1748},{"edgeType":"contains","source":1501,"target":2154},{"edgeType":"calls","source":2588,"target":1331},{"edgeType":"calls","source":2659,"target":187},{"edgeType":"contains","source":5,"target":174},{"edgeType":"contains","source":1,"target":298},{"edgeType":"contains","source":1045,"target":1230},{"edgeType":"imports","source":1836,"target":294},{"edgeType":"contains","source":992,"target":1023},{"edgeType":"calls","source":1159,"target":973},{"edgeType":"contains","source":293,"target":1816},{"edgeType":"calls","source":2565,"target":194},{"edgeType":"contains","source":117,"target":136},{"edgeType":"calls","source":2702,"target":1497},{"edgeType":"contains","source":283,"target":804},{"edgeType":"contains","source":282,"target":835},{"edgeType":"contains","source":1234,"target":2504},{"edgeType":"contains","source":119,"target":2717},{"edgeType":"contains","source":2471,"target":2475},{"edgeType":"contains","source":1625,"target":1482},{"edgeType":"contains","source":2075,"target":2330},{"edgeType":"contains","source":2727,"target":2731},{"edgeType":"contains","source":450,"target":648},{"edgeType":"calls","source":1833,"target":1483},{"edgeType":"contains","source":303,"target":977},{"edgeType":"imports","source":135,"target":438},{"edgeType":"contains","source":121,"target":2390},{"edgeType":"contains","source":119,"target":2452},{"edgeType":"contains","source":101,"target":104},{"edgeType":"calls","source":2433,"target":2437},{"edgeType":"contains","source":427,"target":2153},{"edgeType":"contains","source":1176,"target":2189},{"edgeType":"calls","source":2318,"target":1774},{"edgeType":"calls","source":2541,"target":675},{"edgeType":"calls","source":2588,"target":1332},{"edgeType":"contains","source":1414,"target":1417},{"edgeType":"contains","source":293,"target":1815},{"edgeType":"contains","source":50,"target":69},{"edgeType":"contains","source":283,"target":774},{"edgeType":"contains","source":282,"target":805},{"edgeType":"imports","source":88,"target":91},{"edgeType":"contains","source":119,"target":2687},{"edgeType":"calls","source":1429,"target":492},{"edgeType":"contains","source":843,"target":855},{"edgeType":"contains","source":430,"target":2031},{"edgeType":"contains","source":1794,"target":2557},{"edgeType":"contains","source":1,"target":3},{"edgeType":"contains","source":121,"target":2360},{"edgeType":"calls","source":2071,"target":673},{"edgeType":"contains","source":5,"target":143},{"edgeType":"calls","source":2811,"target":2046},{"edgeType":"calls","source":1405,"target":707},{"edgeType":"contains","source":2158,"target":1051},{"edgeType":"contains","source":180,"target":1060},{"edgeType":"calls","source":1994,"target":681},{"edgeType":"contains","source":58,"target":84},{"edgeType":"calls","source":2353,"target":1975},{"edgeType":"contains","source":430,"target":1237},{"edgeType":"calls","source":2096,"target":690},{"edgeType":"contains","source":843,"target":854},{"edgeType":"contains","source":1501,"target":1864},{"edgeType":"calls","source":2479,"target":976},{"edgeType":"contains","source":1,"target":2},{"edgeType":"calls","source":2812,"target":2809},{"edgeType":"calls","source":1788,"target":1253},{"edgeType":"contains","source":1501,"target":1600},{"edgeType":"contains","source":119,"target":2157},{"edgeType":"calls","source":2811,"target":2047},{"edgeType":"contains","source":5,"target":142},{"edgeType":"contains","source":8,"target":49},{"edgeType":"contains","source":465,"target":680},{"edgeType":"contains","source":1116,"target":2168},{"edgeType":"contains","source":298,"target":1629},{"edgeType":"contains","source":1116,"target":2172},{"edgeType":"calls","source":1899,"target":194},{"edgeType":"contains","source":283,"target":776},{"edgeType":"contains","source":282,"target":807},{"edgeType":"contains","source":76,"target":1379},{"edgeType":"contains","source":1234,"target":2474},{"edgeType":"contains","source":1185,"target":1354},{"edgeType":"calls","source":1899,"target":458},{"edgeType":"calls","source":1429,"target":494},{"edgeType":"calls","source":2018,"target":2054},{"edgeType":"calls","source":2813,"target":2775},{"edgeType":"contains","source":465,"target":683},{"edgeType":"contains","source":438,"target":463},{"edgeType":"calls","source":1483,"target":669},{"edgeType":"contains","source":202,"target":1701},{"edgeType":"contains","source":121,"target":2098},{"edgeType":"calls","source":2663,"target":2668},{"edgeType":"calls","source":2672,"target":1332},{"edgeType":"calls","source":1875,"target":673},{"edgeType":"calls","source":2586,"target":563},{"edgeType":"contains","source":1668,"target":1705},{"edgeType":"contains","source":1836,"target":1782},{"edgeType":"contains","source":5,"target":145},{"edgeType":"calls","source":1159,"target":1200},{"edgeType":"calls","source":2811,"target":2044},{"edgeType":"contains","source":450,"target":619},{"edgeType":"contains","source":50,"target":70},{"edgeType":"calls","source":1311,"target":451},{"edgeType":"contains","source":843,"target":856},{"edgeType":"calls","source":2319,"target":2234},{"edgeType":"contains","source":447,"target":448},{"edgeType":"calls","source":1429,"target":493},{"edgeType":"contains","source":1794,"target":2556},{"edgeType":"contains","source":121,"target":2362},{"edgeType":"imports","source":1854,"target":1894},{"edgeType":"contains","source":309,"target":497},{"edgeType":"calls","source":1380,"target":690},{"edgeType":"contains","source":465,"target":682},{"edgeType":"calls","source":2432,"target":2431},{"edgeType":"calls","source":1493,"target":1415},{"edgeType":"contains","source":1222,"target":2319},{"edgeType":"contains","source":119,"target":2159},{"edgeType":"contains","source":1670,"target":1908},{"edgeType":"contains","source":1721,"target":1913},{"edgeType":"calls","source":2811,"target":2045},{"edgeType":"calls","source":2672,"target":1333},{"edgeType":"contains","source":293,"target":1786},{"edgeType":"contains","source":5,"target":144},{"edgeType":"contains","source":1668,"target":1706},{"edgeType":"contains","source":283,"target":778},{"edgeType":"contains","source":282,"target":809},{"edgeType":"calls","source":2368,"target":976},{"edgeType":"calls","source":2199,"target":1194},{"edgeType":"calls","source":1192,"target":1228},{"edgeType":"calls","source":2200,"target":2220},{"edgeType":"contains","source":1052,"target":194},{"edgeType":"calls","source":1994,"target":678},{"edgeType":"contains","source":76,"target":1381},{"edgeType":"contains","source":127,"target":857},{"edgeType":"calls","source":2186,"target":1333},{"edgeType":"contains","source":1176,"target":1635},{"edgeType":"calls","source":1720,"target":1244},{"edgeType":"calls","source":2330,"target":1890},{"edgeType":"calls","source":1438,"target":1530},{"edgeType":"contains","source":92,"target":93},{"edgeType":"calls","source":1909,"target":670},{"edgeType":"calls","source":1626,"target":194},{"edgeType":"contains","source":465,"target":685},{"edgeType":"contains","source":1851,"target":1852},{"edgeType":"calls","source":134,"target":994},{"edgeType":"calls","source":2672,"target":1330},{"edgeType":"contains","source":177,"target":1157},{"edgeType":"calls","source":1069,"target":1077},{"edgeType":"calls","source":2003,"target":1191},{"edgeType":"calls","source":1192,"target":1227},{"edgeType":"imports","source":1854,"target":1892},{"edgeType":"contains","source":119,"target":2690},{"edgeType":"contains","source":1472,"target":1974},{"edgeType":"contains","source":25,"target":54},{"edgeType":"contains","source":465,"target":684},{"edgeType":"contains","source":309,"target":499},{"edgeType":"calls","source":2615,"target":1777},{"edgeType":"calls","source":2615,"target":984},{"edgeType":"contains","source":1,"target":6},{"edgeType":"calls","source":1558,"target":1244},{"edgeType":"calls","source":2672,"target":1331},{"edgeType":"contains","source":265,"target":1599},{"edgeType":"calls","source":1483,"target":662},{"edgeType":"calls","source":2811,"target":2043},{"edgeType":"contains","source":8,"target":53},{"edgeType":"contains","source":5,"target":146},{"edgeType":"imports","source":1854,"target":1891},{"edgeType":"contains","source":119,"target":2693},{"edgeType":"calls","source":118,"target":170},{"edgeType":"calls","source":1771,"target":194},{"edgeType":"calls","source":2167,"target":2184},{"edgeType":"contains","source":121,"target":2367},{"edgeType":"contains","source":119,"target":2429},{"edgeType":"calls","source":2029,"target":1709},{"edgeType":"contains","source":1836,"target":1257},{"edgeType":"calls","source":2186,"target":1331},{"edgeType":"contains","source":309,"target":503},{"edgeType":"calls","source":2564,"target":976},{"edgeType":"calls","source":2429,"target":669},{"edgeType":"calls","source":979,"target":170},{"edgeType":"contains","source":513,"target":785},{"edgeType":"calls","source":2332,"target":2355},{"edgeType":"calls","source":2672,"target":1328},{"edgeType":"calls","source":1490,"target":976},{"edgeType":"contains","source":119,"target":2692},{"edgeType":"calls","source":2167,"target":2185},{"edgeType":"imports","source":1794,"target":843},{"edgeType":"imports","source":1854,"target":1890},{"edgeType":"calls","source":1159,"target":1195},{"edgeType":"contains","source":450,"target":623},{"edgeType":"calls","source":2029,"target":1708},{"edgeType":"contains","source":1794,"target":2560},{"edgeType":"calls","source":2186,"target":1332},{"edgeType":"contains","source":121,"target":2366},{"edgeType":"contains","source":309,"target":502},{"edgeType":"contains","source":430,"target":2036},{"edgeType":"calls","source":2615,"target":982},{"edgeType":"contains","source":1,"target":8},{"edgeType":"calls","source":2666,"target":194},{"edgeType":"contains","source":465,"target":686},{"edgeType":"calls","source":2896,"target":1256},{"edgeType":"contains","source":119,"target":1899},{"edgeType":"calls","source":2672,"target":1329},{"edgeType":"contains","source":304,"target":1185},{"edgeType":"contains","source":478,"target":2133},{"edgeType":"contains","source":282,"target":810},{"edgeType":"contains","source":1836,"target":1792},{"edgeType":"calls","source":1380,"target":681},{"edgeType":"calls","source":1418,"target":1089},{"edgeType":"contains","source":309,"target":505},{"edgeType":"contains","source":1501,"target":1871},{"edgeType":"contains","source":1078,"target":2563},{"edgeType":"calls","source":1899,"target":976},{"edgeType":"contains","source":216,"target":217},{"edgeType":"contains","source":1670,"target":1917},{"edgeType":"calls","source":2186,"target":1329},{"edgeType":"contains","source":121,"target":2105},{"edgeType":"imports","source":135,"target":1813},{"edgeType":"contains","source":352,"target":2078},{"edgeType":"contains","source":1,"target":11},{"edgeType":"contains","source":450,"target":626},{"edgeType":"contains","source":66,"target":110},{"edgeType":"contains","source":119,"target":2695},{"edgeType":"contains","source":119,"target":2694},{"edgeType":"contains","source":87,"target":1836},{"edgeType":"calls","source":313,"target":460},{"edgeType":"contains","source":121,"target":2368},{"edgeType":"calls","source":1418,"target":1088},{"edgeType":"contains","source":465,"target":689},{"edgeType":"calls","source":2186,"target":1330},{"edgeType":"calls","source":2574,"target":665},{"edgeType":"calls","source":2615,"target":451},{"edgeType":"contains","source":1185,"target":1359},{"edgeType":"imports","source":307,"target":446},{"edgeType":"contains","source":1031,"target":1112},{"edgeType":"contains","source":465,"target":688},{"edgeType":"calls","source":1418,"target":1087},{"edgeType":"calls","source":1805,"target":982},{"edgeType":"imports","source":303,"target":306},{"edgeType":"contains","source":1273,"target":1277},{"edgeType":"contains","source":282,"target":812},{"edgeType":"contains","source":283,"target":781},{"edgeType":"calls","source":2557,"target":664},{"edgeType":"calls","source":2672,"target":1327},{"edgeType":"calls","source":2604,"target":1321},{"edgeType":"calls","source":1192,"target":1226},{"edgeType":"contains","source":981,"target":1344},{"edgeType":"contains","source":465,"target":692},{"edgeType":"contains","source":202,"target":1710},{"edgeType":"calls","source":2623,"target":1257},{"edgeType":"calls","source":997,"target":664},{"edgeType":"contains","source":352,"target":2081},{"edgeType":"calls","source":2027,"target":2031},{"edgeType":"contains","source":76,"target":1387},{"edgeType":"calls","source":2186,"target":1327},{"edgeType":"calls","source":2659,"target":670},{"edgeType":"calls","source":1793,"target":1357},{"edgeType":"calls","source":1968,"target":2010},{"edgeType":"contains","source":2877,"target":2287},{"edgeType":"calls","source":2383,"target":1298},{"edgeType":"calls","source":1528,"target":1644},{"edgeType":"contains","source":450,"target":628},{"edgeType":"contains","source":283,"target":784},{"edgeType":"imports","source":1078,"target":1118},{"edgeType":"contains","source":2540,"target":2428},{"edgeType":"contains","source":119,"target":2697},{"edgeType":"calls","source":1517,"target":664},{"edgeType":"contains","source":1273,"target":1274},{"edgeType":"contains","source":66,"target":112},{"edgeType":"calls","source":1633,"target":1296},{"edgeType":"calls","source":2816,"target":1088},{"edgeType":"contains","source":430,"target":2040},{"edgeType":"calls","source":1994,"target":675},{"edgeType":"contains","source":1501,"target":2134},{"edgeType":"calls","source":1926,"target":669},{"edgeType":"contains","source":352,"target":2344},{"edgeType":"calls","source":313,"target":462},{"edgeType":"calls","source":1192,"target":1225},{"edgeType":"calls","source":2228,"target":290},{"edgeType":"contains","source":465,"target":691},{"edgeType":"contains","source":307,"target":1625},{"edgeType":"calls","source":1834,"target":878},{"edgeType":"calls","source":2186,"target":1328},{"edgeType":"contains","source":76,"target":1386},{"edgeType":"calls","source":2330,"target":1885},{"edgeType":"calls","source":1793,"target":1356},{"edgeType":"calls","source":1805,"target":984},{"edgeType":"contains","source":1794,"target":2565},{"edgeType":"contains","source":282,"target":814},{"edgeType":"contains","source":119,"target":2696},{"edgeType":"calls","source":2816,"target":1089},{"edgeType":"calls","source":1833,"target":1697},{"edgeType":"contains","source":1670,"target":1921},{"edgeType":"contains","source":121,"target":2373},{"edgeType":"calls","source":1063,"target":1255},{"edgeType":"contains","source":352,"target":2347},{"edgeType":"calls","source":1771,"target":976},{"edgeType":"contains","source":465,"target":694},{"edgeType":"calls","source":1875,"target":1980},{"edgeType":"contains","source":76,"target":1390},{"edgeType":"contains","source":1185,"target":1364},{"edgeType":"calls","source":1418,"target":1084},{"edgeType":"contains","source":119,"target":2699},{"edgeType":"contains","source":1,"target":15},{"edgeType":"calls","source":2816,"target":1086},{"edgeType":"contains","source":1078,"target":981},{"edgeType":"calls","source":954,"target":670},{"edgeType":"contains","source":450,"target":630},{"edgeType":"calls","source":2096,"target":678},{"edgeType":"calls","source":1292,"target":1290},{"edgeType":"contains","source":121,"target":2372},{"edgeType":"contains","source":352,"target":2346},{"edgeType":"calls","source":1029,"target":194},{"edgeType":"calls","source":1943,"target":664},{"edgeType":"contains","source":309,"target":508},{"edgeType":"calls","source":1244,"target":664},{"edgeType":"calls","source":2260,"target":2203},{"edgeType":"contains","source":465,"target":693},{"edgeType":"calls","source":1875,"target":1979},{"edgeType":"contains","source":76,"target":1389},{"edgeType":"contains","source":77,"target":1358},{"edgeType":"contains","source":1185,"target":1363},{"edgeType":"calls","source":1418,"target":1083},{"edgeType":"contains","source":293,"target":1796},{"edgeType":"contains","source":478,"target":2139},{"edgeType":"contains","source":282,"target":816},{"edgeType":"calls","source":1926,"target":662},{"edgeType":"calls","source":2816,"target":1087},{"edgeType":"contains","source":1,"target":17},{"edgeType":"calls","source":2096,"target":681},{"edgeType":"contains","source":465,"target":696},{"edgeType":"contains","source":1721,"target":1924},{"edgeType":"calls","source":2816,"target":1084},{"edgeType":"calls","source":2676,"target":2253},{"edgeType":"calls","source":2649,"target":976},{"edgeType":"calls","source":1418,"target":1086},{"edgeType":"imports","source":1078,"target":1114},{"edgeType":"calls","source":2270,"target":569},{"edgeType":"contains","source":119,"target":2701},{"edgeType":"calls","source":134,"target":988},{"edgeType":"contains","source":980,"target":1907},{"edgeType":"contains","source":450,"target":632},{"edgeType":"contains","source":352,"target":2348},{"edgeType":"contains","source":176,"target":1726},{"edgeType":"contains","source":121,"target":2374},{"edgeType":"contains","source":1176,"target":2173},{"edgeType":"calls","source":1380,"target":678},{"edgeType":"calls","source":2083,"target":290},{"edgeType":"calls","source":1189,"target":1314},{"edgeType":"contains","source":465,"target":695},{"edgeType":"calls","source":2423,"target":2433},{"edgeType":"calls","source":2816,"target":1085},{"edgeType":"contains","source":76,"target":1391},{"edgeType":"contains","source":117,"target":120},{"edgeType":"calls","source":2672,"target":1321},{"edgeType":"calls","source":1418,"target":1085},{"edgeType":"calls","source":2330,"target":1881},{"edgeType":"contains","source":282,"target":818},{"edgeType":"contains","source":283,"target":787},{"edgeType":"contains","source":446,"target":1019},{"edgeType":"calls","source":1875,"target":1981},{"edgeType":"calls","source":2429,"target":662},{"edgeType":"contains","source":1758,"target":1835},{"edgeType":"calls","source":134,"target":194},{"edgeType":"contains","source":972,"target":1097},{"edgeType":"calls","source":1994,"target":670},{"edgeType":"calls","source":1240,"target":1082},{"edgeType":"contains","source":346,"target":390},{"edgeType":"calls","source":1361,"target":502},{"edgeType":"calls","source":2106,"target":1191},{"edgeType":"calls","source":2319,"target":666},{"edgeType":"contains","source":1335,"target":1707},{"edgeType":"calls","source":442,"target":451},{"edgeType":"calls","source":1312,"target":700},{"edgeType":"imports","source":1234,"target":1809},{"edgeType":"calls","source":2796,"target":2792},{"edgeType":"calls","source":1506,"target":499},{"edgeType":"contains","source":975,"target":1503},{"edgeType":"contains","source":282,"target":788},{"edgeType":"contains","source":966,"target":989},{"edgeType":"contains","source":353,"target":437},{"edgeType":"contains","source":1974,"target":1982},{"edgeType":"contains","source":1472,"target":1953},{"edgeType":"contains","source":223,"target":239},{"edgeType":"contains","source":223,"target":238},{"edgeType":"calls","source":979,"target":187},{"edgeType":"contains","source":1447,"target":2464},{"edgeType":"contains","source":2478,"target":2479},{"edgeType":"contains","source":293,"target":1768},{"edgeType":"imports","source":1078,"target":1361},{"edgeType":"contains","source":119,"target":1876},{"edgeType":"contains","source":17,"target":18},{"edgeType":"contains","source":1222,"target":1244},{"edgeType":"contains","source":283,"target":756},{"edgeType":"imports","source":153,"target":175},{"edgeType":"imports","source":1969,"target":429},{"edgeType":"calls","source":1952,"target":1999},{"edgeType":"calls","source":1426,"target":1657},{"edgeType":"imports","source":1854,"target":1880},{"edgeType":"contains","source":450,"target":600},{"edgeType":"calls","source":2097,"target":1736},{"edgeType":"contains","source":353,"target":436},{"edgeType":"calls","source":2157,"target":1986},{"edgeType":"calls","source":1240,"target":1084},{"edgeType":"contains","source":2493,"target":2539},{"edgeType":"imports","source":135,"target":201},{"edgeType":"contains","source":346,"target":392},{"edgeType":"contains","source":1,"target":1045},{"edgeType":"contains","source":463,"target":465},{"edgeType":"calls","source":1782,"target":666},{"edgeType":"contains","source":1447,"target":2461},{"edgeType":"calls","source":1772,"target":976},{"edgeType":"calls","source":1821,"target":514},{"edgeType":"contains","source":478,"target":2114},{"edgeType":"contains","source":975,"target":1505},{"edgeType":"contains","source":282,"target":790},{"edgeType":"contains","source":197,"target":254},{"edgeType":"contains","source":135,"target":2176},{"edgeType":"calls","source":1550,"target":194},{"edgeType":"contains","source":1078,"target":2540},{"edgeType":"contains","source":2471,"target":2428},{"edgeType":"calls","source":1951,"target":976},{"edgeType":"calls","source":1252,"target":976},{"edgeType":"contains","source":1297,"target":1298},{"edgeType":"calls","source":2623,"target":2604},{"edgeType":"calls","source":1240,"target":1083},{"edgeType":"calls","source":1269,"target":184},{"edgeType":"contains","source":471,"target":480},{"edgeType":"contains","source":96,"target":213},{"edgeType":"calls","source":2173,"target":170},{"edgeType":"contains","source":293,"target":1770},{"edgeType":"contains","source":1447,"target":2462},{"edgeType":"calls","source":1729,"target":194},{"edgeType":"calls","source":2266,"target":194},{"edgeType":"calls","source":2399,"target":1885},{"edgeType":"contains","source":450,"target":602},{"edgeType":"contains","source":283,"target":758},{"edgeType":"calls","source":2677,"target":666},{"edgeType":"calls","source":1798,"target":697},{"edgeType":"imports","source":1447,"target":2075},{"edgeType":"contains","source":430,"target":2015},{"edgeType":"contains","source":1297,"target":1299},{"edgeType":"calls","source":2578,"target":1089},{"edgeType":"imports","source":1615,"target":1622},{"edgeType":"calls","source":2657,"target":2604},{"edgeType":"calls","source":122,"target":325},{"edgeType":"contains","source":2478,"target":2482},{"edgeType":"calls","source":134,"target":1010},{"edgeType":"contains","source":760,"target":773},{"edgeType":"contains","source":478,"target":2116},{"edgeType":"calls","source":1483,"target":680},{"edgeType":"contains","source":1013,"target":1122},{"edgeType":"contains","source":25,"target":1624},{"edgeType":"imports","source":1447,"target":1545},{"edgeType":"contains","source":6,"target":99},{"edgeType":"contains","source":8,"target":37},{"edgeType":"contains","source":283,"target":761},{"edgeType":"contains","source":2156,"target":2158},{"edgeType":"contains","source":135,"target":2178},{"edgeType":"contains","source":975,"target":1507},{"edgeType":"contains","source":1794,"target":2545},{"edgeType":"calls","source":256,"target":664},{"edgeType":"contains","source":223,"target":243},{"edgeType":"contains","source":346,"target":394},{"edgeType":"calls","source":979,"target":184},{"edgeType":"calls","source":1474,"target":1487},{"edgeType":"contains","source":87,"target":1287},{"edgeType":"contains","source":1668,"target":1695},{"edgeType":"contains","source":1501,"target":1851},{"edgeType":"calls","source":2881,"target":682},{"edgeType":"calls","source":122,"target":324},{"edgeType":"calls","source":1922,"target":547},{"edgeType":"calls","source":2482,"target":1688},{"edgeType":"contains","source":293,"target":1772},{"edgeType":"calls","source":1678,"target":976},{"edgeType":"calls","source":2672,"target":290},{"edgeType":"contains","source":478,"target":2115},{"edgeType":"calls","source":1022,"target":435},{"edgeType":"calls","source":118,"target":184},{"edgeType":"contains","source":450,"target":604},{"edgeType":"imports","source":1234,"target":1013},{"edgeType":"contains","source":135,"target":2177},{"edgeType":"contains","source":1794,"target":2018},{"edgeType":"calls","source":2377,"target":451},{"edgeType":"calls","source":2543,"target":326},{"edgeType":"calls","source":2658,"target":1253},{"edgeType":"calls","source":256,"target":663},{"edgeType":"imports","source":1969,"target":425},{"edgeType":"contains","source":223,"target":242},{"edgeType":"contains","source":980,"target":2672},{"edgeType":"contains","source":1031,"target":1091},{"edgeType":"contains","source":25,"target":38},{"edgeType":"calls","source":2818,"target":1314},{"edgeType":"calls","source":979,"target":186},{"edgeType":"contains","source":202,"target":1689},{"edgeType":"calls","source":2149,"target":1173},{"edgeType":"calls","source":2481,"target":1187},{"edgeType":"contains","source":293,"target":1775},{"edgeType":"calls","source":122,"target":327},{"edgeType":"calls","source":2578,"target":1087},{"edgeType":"contains","source":282,"target":795},{"edgeType":"contains","source":298,"target":299},{"edgeType":"contains","source":216,"target":726},{"edgeType":"contains","source":119,"target":2676},{"edgeType":"calls","source":118,"target":187},{"edgeType":"contains","source":135,"target":2180},{"edgeType":"calls","source":128,"target":670},{"edgeType":"calls","source":2382,"target":2407},{"edgeType":"calls","source":1426,"target":1656},{"edgeType":"contains","source":223,"target":245},{"edgeType":"contains","source":1111,"target":1521},{"edgeType":"contains","source":346,"target":396},{"edgeType":"contains","source":1472,"target":1955},{"edgeType":"calls","source":2578,"target":1088},{"edgeType":"imports","source":1447,"target":1013},{"edgeType":"contains","source":843,"target":844},{"edgeType":"calls","source":2311,"target":1173},{"edgeType":"calls","source":2097,"target":1729},{"edgeType":"calls","source":1361,"target":499},{"edgeType":"contains","source":1447,"target":2466},{"edgeType":"calls","source":1312,"target":697},{"edgeType":"calls","source":1516,"target":451},{"edgeType":"contains","source":1392,"target":1793},{"edgeType":"contains","source":283,"target":763},{"edgeType":"imports","source":980,"target":429},{"edgeType":"contains","source":2478,"target":2481},{"edgeType":"calls","source":1380,"target":703},{"edgeType":"contains","source":282,"target":793},{"edgeType":"calls","source":118,"target":186},{"edgeType":"contains","source":450,"target":606},{"edgeType":"calls","source":2884,"target":2437},{"edgeType":"contains","source":1794,"target":2544},{"edgeType":"contains","source":223,"target":244},{"edgeType":"calls","source":1661,"target":976},{"edgeType":"calls","source":2219,"target":326},{"edgeType":"contains","source":121,"target":2088},{"edgeType":"contains","source":1116,"target":1633},{"edgeType":"contains","source":2478,"target":2486},{"edgeType":"contains","source":450,"target":610},{"edgeType":"calls","source":122,"target":321},{"edgeType":"calls","source":2578,"target":1085},{"edgeType":"contains","source":282,"target":797},{"edgeType":"contains","source":298,"target":301},{"edgeType":"contains","source":119,"target":2679},{"edgeType":"contains","source":135,"target":2183},{"edgeType":"calls","source":721,"target":514},{"edgeType":"contains","source":119,"target":2678},{"edgeType":"contains","source":2250,"target":2155},{"edgeType":"calls","source":1994,"target":690},{"edgeType":"calls","source":1490,"target":194},{"edgeType":"calls","source":979,"target":973},{"edgeType":"contains","source":74,"target":1167},{"edgeType":"contains","source":223,"target":247},{"edgeType":"contains","source":121,"target":2352},{"edgeType":"contains","source":346,"target":398},{"edgeType":"contains","source":352,"target":2326},{"edgeType":"contains","source":1111,"target":1523},{"edgeType":"contains","source":309,"target":488},{"edgeType":"contains","source":1670,"target":1901},{"edgeType":"contains","source":1060,"target":1254},{"edgeType":"calls","source":2452,"target":2085},{"edgeType":"calls","source":1402,"target":1336},{"edgeType":"contains","source":1310,"target":1434},{"edgeType":"contains","source":972,"target":1075},{"edgeType":"contains","source":2478,"target":2487},{"edgeType":"contains","source":1668,"target":1699},{"edgeType":"contains","source":283,"target":765},{"edgeType":"calls","source":122,"target":320},{"edgeType":"calls","source":2578,"target":1086},{"edgeType":"contains","source":1176,"target":2150},{"edgeType":"contains","source":265,"target":266},{"edgeType":"calls","source":1417,"target":1399},{"edgeType":"contains","source":119,"target":2677},{"edgeType":"calls","source":2019,"target":2028},{"edgeType":"imports","source":1447,"target":2085},{"edgeType":"contains","source":223,"target":246},{"edgeType":"contains","source":1668,"target":1700},{"edgeType":"contains","source":430,"target":2021},{"edgeType":"contains","source":843,"target":849},{"edgeType":"contains","source":1031,"target":1099},{"edgeType":"contains","source":1794,"target":2547},{"edgeType":"calls","source":1922,"target":546},{"edgeType":"contains","source":450,"target":612},{"edgeType":"contains","source":282,"target":799},{"edgeType":"calls","source":1292,"target":1314},{"edgeType":"calls","source":2578,"target":1083},{"edgeType":"imports","source":1543,"target":1222},{"edgeType":"imports","source":1078,"target":1102},{"edgeType":"contains","source":64,"target":157},{"edgeType":"contains","source":119,"target":2681},{"edgeType":"calls","source":1635,"target":194},{"edgeType":"calls","source":2353,"target":1980},{"edgeType":"calls","source":2368,"target":194},{"edgeType":"calls","source":2089,"target":1708},{"edgeType":"contains","source":352,"target":2328},{"edgeType":"contains","source":223,"target":249},{"edgeType":"calls","source":1468,"target":878},{"edgeType":"contains","source":1178,"target":241},{"edgeType":"contains","source":309,"target":490},{"edgeType":"contains","source":2160,"target":1243},{"edgeType":"contains","source":346,"target":400},{"edgeType":"contains","source":2197,"target":2210},{"edgeType":"calls","source":1695,"target":976},{"edgeType":"imports","source":352,"target":353},{"edgeType":"contains","source":980,"target":1622},{"edgeType":"contains","source":1668,"target":1697},{"edgeType":"contains","source":126,"target":1670},{"edgeType":"contains","source":304,"target":1173},{"edgeType":"calls","source":721,"target":515},{"edgeType":"contains","source":2792,"target":2793},{"edgeType":"contains","source":283,"target":767},{"edgeType":"calls","source":1907,"target":1010},{"edgeType":"calls","source":2578,"target":1084},{"edgeType":"calls","source":2353,"target":1981},{"edgeType":"calls","source":122,"target":322},{"edgeType":"calls","source":2089,"target":1709},{"edgeType":"contains","source":1,"target":260},{"edgeType":"contains","source":1501,"target":2118},{"edgeType":"calls","source":1385,"target":1336},{"edgeType":"calls","source":285,"target":290},{"edgeType":"contains","source":223,"target":248},{"edgeType":"calls","source":217,"target":284},{"edgeType":"contains","source":309,"target":489},{"edgeType":"calls","source":1879,"target":556},{"edgeType":"calls","source":1312,"target":428},{"edgeType":"contains","source":76,"target":1370},{"edgeType":"contains","source":121,"target":2089},{"edgeType":"contains","source":1794,"target":2553},{"edgeType":"contains","source":1078,"target":2551},{"edgeType":"contains","source":76,"target":1373},{"edgeType":"contains","source":478,"target":2124},{"edgeType":"calls","source":2811,"target":2050},{"edgeType":"contains","source":1501,"target":1594},{"edgeType":"calls","source":2483,"target":326},{"edgeType":"contains","source":282,"target":801},{"edgeType":"contains","source":1758,"target":1819},{"edgeType":"calls","source":1264,"target":326},{"edgeType":"contains","source":64,"target":159},{"edgeType":"contains","source":450,"target":614},{"edgeType":"calls","source":2018,"target":2056},{"edgeType":"calls","source":1352,"target":1561},{"edgeType":"contains","source":126,"target":352},{"edgeType":"calls","source":1269,"target":170},{"edgeType":"calls","source":1763,"target":1769},{"edgeType":"contains","source":135,"target":1922},{"edgeType":"calls","source":1159,"target":1202},{"edgeType":"contains","source":1222,"target":2316},{"edgeType":"contains","source":1668,"target":1703},{"edgeType":"contains","source":309,"target":492},{"edgeType":"calls","source":2764,"target":1393},{"edgeType":"calls","source":1192,"target":1236},{"edgeType":"calls","source":2622,"target":2624},{"edgeType":"calls","source":2752,"target":2558},{"edgeType":"imports","source":1854,"target":1621},{"edgeType":"contains","source":465,"target":677},{"edgeType":"calls","source":2172,"target":1776},{"edgeType":"contains","source":1111,"target":1527},{"edgeType":"contains","source":843,"target":850},{"edgeType":"calls","source":1756,"target":664},{"edgeType":"calls","source":1795,"target":512},{"edgeType":"contains","source":1721,"target":1910},{"edgeType":"calls","source":2764,"target":1394},{"edgeType":"contains","source":478,"target":2123},{"edgeType":"contains","source":283,"target":769},{"edgeType":"calls","source":2578,"target":1082},{"edgeType":"calls","source":1824,"target":670},{"edgeType":"contains","source":64,"target":158},{"edgeType":"calls","source":1532,"target":1530},{"edgeType":"calls","source":2353,"target":1979},{"edgeType":"calls","source":2018,"target":2055},{"edgeType":"calls","source":1352,"target":1560},{"edgeType":"contains","source":305,"target":879},{"edgeType":"calls","source":1968,"target":1755},{"edgeType":"contains","source":5,"target":138},{"edgeType":"calls","source":1192,"target":1235},{"edgeType":"calls","source":1159,"target":1201},{"edgeType":"calls","source":2382,"target":2398},{"edgeType":"contains","source":438,"target":1252},{"edgeType":"contains","source":282,"target":803},{"edgeType":"contains","source":119,"target":2685},{"edgeType":"calls","source":2353,"target":1976},{"edgeType":"contains","source":1222,"target":1785},{"edgeType":"contains","source":450,"target":616},{"edgeType":"contains","source":2075,"target":2296},{"edgeType":"contains","source":843,"target":853},{"edgeType":"calls","source":122,"target":319},{"edgeType":"contains","source":121,"target":2358},{"edgeType":"calls","source":979,"target":971},{"edgeType":"contains","source":309,"target":494},{"edgeType":"contains","source":126,"target":1411},{"edgeType":"calls","source":313,"target":476},{"edgeType":"contains","source":478,"target":2126},{"edgeType":"contains","source":1,"target":265},{"edgeType":"calls","source":2811,"target":2048},{"edgeType":"contains","source":465,"target":679},{"edgeType":"calls","source":1224,"target":1039},{"edgeType":"contains","source":430,"target":442},{"edgeType":"contains","source":76,"target":1374},{"edgeType":"calls","source":2172,"target":1774},{"edgeType":"calls","source":2811,"target":2049},{"edgeType":"contains","source":478,"target":2125},{"edgeType":"contains","source":283,"target":771},{"edgeType":"calls","source":2353,"target":1977},{"edgeType":"contains","source":119,"target":2684},{"edgeType":"contains","source":843,"target":852},{"edgeType":"contains","source":302,"target":975},{"edgeType":"contains","source":2075,"target":2297},{"edgeType":"calls","source":1795,"target":514},{"edgeType":"calls","source":2366,"target":2367},{"edgeType":"contains","source":67,"target":68},{"edgeType":"contains","source":1472,"target":1964},{"edgeType":"calls","source":2018,"target":2057},{"edgeType":"calls","source":122,"target":318},{"edgeType":"calls","source":161,"target":166},{"edgeType":"contains","source":478,"target":1596},{"edgeType":"contains","source":346,"target":403},{"edgeType":"contains","source":5,"target":140},{"edgeType":"contains","source":309,"target":493},{"edgeType":"contains","source":430,"target":2027},{"edgeType":"calls","source":1352,"target":1562},{"edgeType":"calls","source":2878,"target":2879},{"edgeType":"imports","source":135,"target":1792},{"edgeType":"contains","source":1668,"target":1702},{"edgeType":"calls","source":2812,"target":2811},{"edgeType":"contains","source":1057,"target":1059},{"edgeType":"calls","source":2313,"target":670},{"edgeType":"contains","source":282,"target":772},{"edgeType":"contains","source":283,"target":741},{"edgeType":"calls","source":1426,"target":948},{"edgeType":"contains","source":438,"target":1750},{"edgeType":"calls","source":2664,"target":1945},{"edgeType":"calls","source":1956,"target":1959},{"edgeType":"contains","source":1472,"target":1936},{"edgeType":"imports","source":1447,"target":1863},{"edgeType":"calls","source":977,"target":1125},{"edgeType":"calls","source":1188,"target":662},{"edgeType":"calls","source":1263,"target":451},{"edgeType":"calls","source":2199,"target":505},{"edgeType":"calls","source":1340,"target":971},{"edgeType":"contains","source":1447,"target":2447},{"edgeType":"calls","source":1874,"target":1858},{"edgeType":"calls","source":2658,"target":2660},{"edgeType":"calls","source":2179,"target":1918},{"edgeType":"calls","source":1315,"target":425},{"edgeType":"calls","source":1899,"target":290},{"edgeType":"calls","source":1254,"target":1258},{"edgeType":"contains","source":1873,"target":1926},{"edgeType":"contains","source":1057,"target":1058},{"edgeType":"contains","source":1472,"target":1937},{"edgeType":"contains","source":450,"target":584},{"edgeType":"calls","source":977,"target":1124},{"edgeType":"contains","source":305,"target":851},{"edgeType":"calls","source":2336,"target":2337},{"edgeType":"calls","source":2363,"target":1500},{"edgeType":"calls","source":2627,"target":451},{"edgeType":"contains","source":346,"target":372},{"edgeType":"calls","source":2203,"target":2232},{"edgeType":"contains","source":25,"target":1603},{"edgeType":"calls","source":2729,"target":460},{"edgeType":"calls","source":1874,"target":1857},{"edgeType":"imports","source":1447,"target":1334},{"edgeType":"contains","source":293,"target":1751},{"edgeType":"calls","source":461,"target":475},{"edgeType":"contains","source":1057,"target":1061},{"edgeType":"contains","source":1794,"target":2258},{"edgeType":"contains","source":1969,"target":1325},{"edgeType":"contains","source":223,"target":225},{"edgeType":"contains","source":190,"target":191},{"edgeType":"calls","source":1340,"target":973},{"edgeType":"calls","source":2313,"target":1197},{"edgeType":"contains","source":1472,"target":1934},{"edgeType":"calls","source":2815,"target":2812},{"edgeType":"calls","source":2199,"target":503},{"edgeType":"contains","source":1670,"target":1874},{"edgeType":"contains","source":293,"target":1754},{"edgeType":"contains","source":1407,"target":1571},{"edgeType":"calls","source":2681,"target":1945},{"edgeType":"calls","source":1352,"target":1394},{"edgeType":"calls","source":2083,"target":666},{"edgeType":"calls","source":1771,"target":296},{"edgeType":"contains","source":975,"target":1488},{"edgeType":"imports","source":88,"target":123},{"edgeType":"contains","source":283,"target":742},{"edgeType":"contains","source":74,"target":1407},{"edgeType":"contains","source":980,"target":2654},{"edgeType":"contains","source":1222,"target":1757},{"edgeType":"calls","source":2664,"target":1944},{"edgeType":"contains","source":223,"target":224},{"edgeType":"contains","source":1836,"target":164},{"edgeType":"calls","source":461,"target":474},{"edgeType":"contains","source":346,"target":374},{"edgeType":"contains","source":352,"target":2302},{"edgeType":"contains","source":1545,"target":465},{"edgeType":"contains","source":67,"target":1096},{"edgeType":"imports","source":1113,"target":1116},{"edgeType":"calls","source":1352,"target":1393},{"edgeType":"calls","source":1874,"target":1859},{"edgeType":"calls","source":1591,"target":326},{"edgeType":"contains","source":180,"target":1028},{"edgeType":"contains","source":96,"target":464},{"edgeType":"calls","source":2682,"target":326},{"edgeType":"calls","source":2085,"target":1656},{"edgeType":"contains","source":165,"target":1232},{"edgeType":"contains","source":119,"target":2658},{"edgeType":"contains","source":197,"target":240},{"edgeType":"calls","source":1257,"target":1162},{"edgeType":"contains","source":446,"target":449},{"edgeType":"contains","source":221,"target":289},{"edgeType":"contains","source":346,"target":378},{"edgeType":"contains","source":1873,"target":1929},{"edgeType":"calls","source":2796,"target":2077},{"edgeType":"contains","source":457,"target":2222},{"edgeType":"calls","source":2187,"target":2194},{"edgeType":"contains","source":980,"target":2657},{"edgeType":"contains","source":1031,"target":1076},{"edgeType":"contains","source":2428,"target":2430},{"edgeType":"contains","source":1447,"target":2451},{"edgeType":"calls","source":1436,"target":1162},{"edgeType":"contains","source":124,"target":125},{"edgeType":"calls","source":1664,"target":436},{"edgeType":"calls","source":2600,"target":2604},{"edgeType":"calls","source":2085,"target":1657},{"edgeType":"contains","source":450,"target":588},{"edgeType":"contains","source":282,"target":775},{"edgeType":"contains","source":283,"target":744},{"edgeType":"calls","source":1257,"target":1161},{"edgeType":"calls","source":1757,"target":1781},{"edgeType":"contains","source":438,"target":1753},{"edgeType":"contains","source":1472,"target":1941},{"edgeType":"imports","source":975,"target":107},{"edgeType":"contains","source":223,"target":226},{"edgeType":"contains","source":352,"target":2305},{"edgeType":"contains","source":980,"target":2656},{"edgeType":"contains","source":2428,"target":2431},{"edgeType":"calls","source":338,"target":317},{"edgeType":"calls","source":2330,"target":669},{"edgeType":"contains","source":2334,"target":1116},{"edgeType":"contains","source":346,"target":376},{"edgeType":"calls","source":2085,"target":1922},{"edgeType":"calls","source":1436,"target":1161},{"edgeType":"contains","source":25,"target":1607},{"edgeType":"calls","source":2681,"target":1944},{"edgeType":"contains","source":96,"target":466},{"edgeType":"contains","source":119,"target":2660},{"edgeType":"contains","source":450,"target":591},{"edgeType":"contains","source":352,"target":2308},{"edgeType":"contains","source":223,"target":229},{"edgeType":"contains","source":221,"target":291},{"edgeType":"contains","source":980,"target":2659},{"edgeType":"contains","source":346,"target":380},{"edgeType":"contains","source":58,"target":59},{"edgeType":"calls","source":1766,"target":976},{"edgeType":"contains","source":1447,"target":2449},{"edgeType":"calls","source":2840,"target":976},{"edgeType":"calls","source":2175,"target":186},{"edgeType":"contains","source":1794,"target":1998},{"edgeType":"contains","source":8,"target":23},{"edgeType":"contains","source":6,"target":85},{"edgeType":"contains","source":283,"target":747},{"edgeType":"contains","source":282,"target":777},{"edgeType":"calls","source":2661,"target":976},{"edgeType":"contains","source":165,"target":1233},{"edgeType":"contains","source":8,"target":286},{"edgeType":"contains","source":450,"target":590},{"edgeType":"contains","source":223,"target":228},{"edgeType":"contains","source":1745,"target":1668},{"edgeType":"contains","source":457,"target":2223},{"edgeType":"imports","source":1234,"target":1325},{"edgeType":"imports","source":1447,"target":1063},{"edgeType":"calls","source":1528,"target":690},{"edgeType":"contains","source":430,"target":2003},{"edgeType":"contains","source":1472,"target":1939},{"edgeType":"contains","source":352,"target":2307},{"edgeType":"imports","source":1078,"target":1404},{"edgeType":"calls","source":164,"target":164},{"edgeType":"calls","source":2175,"target":187},{"edgeType":"calls","source":1024,"target":194},{"edgeType":"contains","source":119,"target":2662},{"edgeType":"contains","source":96,"target":468},{"edgeType":"contains","source":305,"target":860},{"edgeType":"calls","source":2465,"target":1235},{"edgeType":"imports","source":114,"target":119},{"edgeType":"contains","source":223,"target":231},{"edgeType":"contains","source":346,"target":382},{"edgeType":"contains","source":1447,"target":2455},{"edgeType":"contains","source":25,"target":27},{"edgeType":"contains","source":2040,"target":2042},{"edgeType":"calls","source":1878,"target":669},{"edgeType":"contains","source":980,"target":2661},{"edgeType":"calls","source":1340,"target":170},{"edgeType":"calls","source":2672,"target":1161},{"edgeType":"imports","source":1234,"target":1338},{"edgeType":"contains","source":283,"target":749},{"edgeType":"contains","source":282,"target":780},{"edgeType":"calls","source":2175,"target":184},{"edgeType":"imports","source":1472,"target":304},{"edgeType":"contains","source":1758,"target":1799},{"edgeType":"calls","source":2253,"target":673},{"edgeType":"contains","source":1794,"target":2005},{"edgeType":"calls","source":2465,"target":1236},{"edgeType":"contains","source":223,"target":230},{"edgeType":"contains","source":352,"target":2309},{"edgeType":"contains","source":2428,"target":2435},{"edgeType":"contains","source":1447,"target":2456},{"edgeType":"calls","source":1798,"target":241},{"edgeType":"calls","source":1426,"target":1731},{"edgeType":"contains","source":25,"target":26},{"edgeType":"calls","source":2168,"target":666},{"edgeType":"calls","source":2672,"target":1162},{"edgeType":"calls","source":1500,"target":1551},{"edgeType":"calls","source":2005,"target":2016},{"edgeType":"calls","source":1798,"target":505},{"edgeType":"contains","source":1,"target":1034},{"edgeType":"contains","source":1758,"target":1800},{"edgeType":"contains","source":282,"target":779},{"edgeType":"calls","source":2084,"target":1945},{"edgeType":"contains","source":353,"target":431},{"edgeType":"contains","source":223,"target":233},{"edgeType":"calls","source":1757,"target":1780},{"edgeType":"contains","source":121,"target":2338},{"edgeType":"contains","source":1794,"target":2002},{"edgeType":"contains","source":1222,"target":1500},{"edgeType":"contains","source":2428,"target":2432},{"edgeType":"contains","source":346,"target":384},{"edgeType":"contains","source":1080,"target":1413},{"edgeType":"contains","source":1111,"target":1509},{"edgeType":"calls","source":977,"target":326},{"edgeType":"contains","source":980,"target":2663},{"edgeType":"contains","source":1447,"target":2453},{"edgeType":"calls","source":1788,"target":290},{"edgeType":"contains","source":25,"target":29},{"edgeType":"contains","source":50,"target":1368},{"edgeType":"calls","source":2330,"target":662},{"edgeType":"contains","source":450,"target":595},{"edgeType":"contains","source":119,"target":2664},{"edgeType":"imports","source":1969,"target":1013},{"edgeType":"contains","source":305,"target":861},{"edgeType":"calls","source":1361,"target":1106},{"edgeType":"calls","source":1798,"target":508},{"edgeType":"calls","source":1590,"target":878},{"edgeType":"calls","source":2458,"target":1187},{"edgeType":"imports","source":1447,"target":1868},{"edgeType":"contains","source":471,"target":472},{"edgeType":"contains","source":1836,"target":2022},{"edgeType":"contains","source":2106,"target":2109},{"edgeType":"contains","source":293,"target":1761},{"edgeType":"contains","source":1447,"target":2454},{"edgeType":"contains","source":1335,"target":1698},{"edgeType":"imports","source":165,"target":123},{"edgeType":"contains","source":450,"target":594},{"edgeType":"contains","source":283,"target":750},{"edgeType":"calls","source":995,"target":296},{"edgeType":"contains","source":1472,"target":1948},{"edgeType":"contains","source":126,"target":1392},{"edgeType":"contains","source":223,"target":235},{"edgeType":"calls","source":1075,"target":982},{"edgeType":"contains","source":346,"target":386},{"edgeType":"calls","source":1869,"target":680},{"edgeType":"contains","source":983,"target":987},{"edgeType":"contains","source":2428,"target":2438},{"edgeType":"contains","source":1447,"target":2459},{"edgeType":"contains","source":2488,"target":2428},{"edgeType":"calls","source":990,"target":974},{"edgeType":"calls","source":1527,"target":976},{"edgeType":"contains","source":119,"target":2138},{"edgeType":"calls","source":1919,"target":451},{"edgeType":"contains","source":293,"target":1765},{"edgeType":"contains","source":1969,"target":1868},{"edgeType":"calls","source":1312,"target":241},{"edgeType":"contains","source":116,"target":117},{"edgeType":"calls","source":2575,"target":2578},{"edgeType":"imports","source":1234,"target":1334},{"edgeType":"calls","source":1238,"target":1478},{"edgeType":"contains","source":450,"target":597},{"edgeType":"contains","source":1745,"target":1942},{"edgeType":"contains","source":353,"target":433},{"edgeType":"calls","source":2084,"target":1944},{"edgeType":"contains","source":2493,"target":2538},{"edgeType":"contains","source":223,"target":234},{"edgeType":"contains","source":8,"target":28},{"edgeType":"calls","source":2253,"target":669},{"edgeType":"contains","source":74,"target":96},{"edgeType":"calls","source":1340,"target":958},{"edgeType":"calls","source":951,"target":1125},{"edgeType":"calls","source":213,"target":220},{"edgeType":"calls","source":2543,"target":664},{"edgeType":"calls","source":122,"target":134},{"edgeType":"contains","source":11,"target":199},{"edgeType":"contains","source":1335,"target":1704},{"edgeType":"calls","source":2029,"target":1268},{"edgeType":"contains","source":50,"target":1369},{"edgeType":"contains","source":25,"target":30},{"edgeType":"contains","source":1429,"target":1433},{"edgeType":"contains","source":463,"target":1250},{"edgeType":"calls","source":2475,"target":1187},{"edgeType":"calls","source":2040,"target":1191},{"edgeType":"imports","source":1447,"target":1338},{"edgeType":"calls","source":1723,"target":976},{"edgeType":"contains","source":283,"target":752},{"edgeType":"contains","source":282,"target":783},{"edgeType":"contains","source":223,"target":237},{"edgeType":"calls","source":1075,"target":984},{"edgeType":"contains","source":2428,"target":2436},{"edgeType":"contains","source":255,"target":1095},{"edgeType":"contains","source":1472,"target":1946},{"edgeType":"contains","source":346,"target":388},{"edgeType":"contains","source":131,"target":446},{"edgeType":"contains","source":1447,"target":2457},{"edgeType":"contains","source":50,"target":51},{"edgeType":"calls","source":1426,"target":673},{"edgeType":"contains","source":282,"target":786},{"edgeType":"contains","source":25,"target":1090},{"edgeType":"contains","source":197,"target":250},{"edgeType":"calls","source":1352,"target":1646},{"edgeType":"contains","source":50,"target":1372},{"edgeType":"contains","source":450,"target":599},{"edgeType":"contains","source":353,"target":435},{"edgeType":"calls","source":1715,"target":170},{"edgeType":"contains","source":1013,"target":1115},{"edgeType":"calls","source":1352,"target":1645},{"edgeType":"contains","source":2493,"target":2536},{"edgeType":"calls","source":2219,"target":664},{"edgeType":"imports","source":114,"target":1435},{"edgeType":"calls","source":1912,"target":669},{"edgeType":"imports","source":165,"target":119},{"edgeType":"calls","source":1500,"target":1549},{"edgeType":"calls","source":1528,"target":681},{"edgeType":"contains","source":283,"target":754},{"edgeType":"calls","source":2672,"target":2741},{"edgeType":"contains","source":1335,"target":1438},{"edgeType":"imports","source":1836,"target":904},{"edgeType":"contains","source":1758,"target":1802},{"edgeType":"contains","source":116,"target":1439},{"edgeType":"contains","source":353,"target":434},{"edgeType":"calls","source":1798,"target":503},{"edgeType":"contains","source":972,"target":1064},{"edgeType":"calls","source":1819,"target":1202},{"edgeType":"calls","source":2173,"target":1327},{"edgeType":"contains","source":346,"target":357},{"edgeType":"contains","source":1411,"target":1432},{"edgeType":"calls","source":1253,"target":1307},{"edgeType":"imports","source":1447,"target":2375},{"edgeType":"contains","source":1335,"target":1674},{"edgeType":"contains","source":304,"target":1395},{"edgeType":"calls","source":2083,"target":681},{"edgeType":"contains","source":1435,"target":1481},{"edgeType":"contains","source":1868,"target":2064},{"edgeType":"calls","source":2150,"target":1512},{"edgeType":"calls","source":1816,"target":1823},{"edgeType":"calls","source":1253,"target":1306},{"edgeType":"calls","source":1715,"target":2047},{"edgeType":"calls","source":1942,"target":1088},{"edgeType":"contains","source":282,"target":755},{"edgeType":"contains","source":283,"target":724},{"edgeType":"calls","source":977,"target":878},{"edgeType":"calls","source":1558,"target":572},{"edgeType":"calls","source":1340,"target":195},{"edgeType":"calls","source":2168,"target":690},{"edgeType":"contains","source":1472,"target":1920},{"edgeType":"calls","source":2883,"target":194},{"edgeType":"calls","source":1867,"target":1827},{"edgeType":"contains","source":2551,"target":2561},{"edgeType":"imports","source":1234,"target":1315},{"edgeType":"calls","source":1819,"target":1201},{"edgeType":"calls","source":2150,"target":984},{"edgeType":"calls","source":2173,"target":1328},{"edgeType":"contains","source":87,"target":457},{"edgeType":"calls","source":1826,"target":984},{"edgeType":"contains","source":880,"target":979},{"edgeType":"calls","source":2058,"target":1191},{"edgeType":"contains","source":346,"target":356},{"edgeType":"calls","source":1715,"target":2046},{"edgeType":"calls","source":1942,"target":1087},{"edgeType":"calls","source":1253,"target":1305},{"edgeType":"contains","source":1868,"target":2065},{"edgeType":"calls","source":1952,"target":1834},{"edgeType":"calls","source":1600,"target":326},{"edgeType":"calls","source":1733,"target":1752},{"edgeType":"contains","source":197,"target":218},{"edgeType":"contains","source":1116,"target":1590},{"edgeType":"calls","source":1819,"target":1200},{"edgeType":"calls","source":2010,"target":300},{"edgeType":"calls","source":1715,"target":196},{"edgeType":"contains","source":450,"target":567},{"edgeType":"contains","source":265,"target":1017},{"edgeType":"contains","source":346,"target":359},{"edgeType":"contains","source":858,"target":1664},{"edgeType":"contains","source":304,"target":1397},{"edgeType":"contains","source":293,"target":1738},{"edgeType":"calls","source":1191,"target":1117},{"edgeType":"contains","source":1435,"target":1479},{"edgeType":"calls","source":2022,"target":460},{"edgeType":"contains","source":463,"target":1224},{"edgeType":"contains","source":1111,"target":1484},{"edgeType":"calls","source":2319,"target":2349},{"edgeType":"contains","source":282,"target":757},{"edgeType":"calls","source":2120,"target":326},{"edgeType":"calls","source":2610,"target":1256},{"edgeType":"contains","source":1222,"target":1740},{"edgeType":"imports","source":975,"target":91},{"edgeType":"calls","source":1715,"target":2049},{"edgeType":"calls","source":2167,"target":1776},{"edgeType":"contains","source":346,"target":358},{"edgeType":"calls","source":2228,"target":678},{"edgeType":"calls","source":2247,"target":2203},{"edgeType":"calls","source":2150,"target":982},{"edgeType":"calls","source":1888,"target":385},{"edgeType":"calls","source":2646,"target":669},{"edgeType":"contains","source":1335,"target":1673},{"edgeType":"calls","source":1253,"target":1308},{"edgeType":"contains","source":1435,"target":1480},{"edgeType":"calls","source":1715,"target":2048},{"edgeType":"contains","source":1868,"target":2063},{"edgeType":"contains","source":1679,"target":1051},{"edgeType":"calls","source":1942,"target":1089},{"edgeType":"contains","source":19,"target":189},{"edgeType":"contains","source":160,"target":1367},{"edgeType":"imports","source":1836,"target":91},{"edgeType":"calls","source":1340,"target":196},{"edgeType":"calls","source":1558,"target":573},{"edgeType":"contains","source":980,"target":2637},{"edgeType":"contains","source":457,"target":2202},{"edgeType":"contains","source":450,"target":569},{"edgeType":"imports","source":307,"target":981},{"edgeType":"contains","source":305,"target":836},{"edgeType":"contains","source":346,"target":361},{"edgeType":"calls","source":2172,"target":1354},{"edgeType":"contains","source":1969,"target":1315},{"edgeType":"calls","source":2228,"target":675},{"edgeType":"contains","source":981,"target":1024},{"edgeType":"calls","source":1993,"target":296},{"edgeType":"imports","source":1113,"target":304},{"edgeType":"contains","source":11,"target":968},{"edgeType":"contains","source":76,"target":1067},{"edgeType":"calls","source":1775,"target":976},{"edgeType":"contains","source":76,"target":1068},{"edgeType":"contains","source":975,"target":1474},{"edgeType":"calls","source":1942,"target":1084},{"edgeType":"contains","source":282,"target":759},{"edgeType":"contains","source":1111,"target":1486},{"edgeType":"contains","source":15,"target":52},{"edgeType":"calls","source":1253,"target":1302},{"edgeType":"calls","source":1715,"target":2043},{"edgeType":"contains","source":438,"target":1737},{"edgeType":"calls","source":2072,"target":1546},{"edgeType":"calls","source":2642,"target":2640},{"edgeType":"calls","source":2167,"target":1774},{"edgeType":"imports","source":980,"target":1257},{"edgeType":"contains","source":346,"target":360},{"edgeType":"contains","source":293,"target":1739},{"edgeType":"calls","source":1192,"target":1343},{"edgeType":"calls","source":1942,"target":1083},{"edgeType":"imports","source":1234,"target":782},{"edgeType":"contains","source":76,"target":1066},{"edgeType":"calls","source":2791,"target":664},{"edgeType":"contains","source":1414,"target":1080},{"edgeType":"contains","source":283,"target":727},{"edgeType":"contains","source":430,"target":1191},{"edgeType":"contains","source":450,"target":571},{"edgeType":"calls","source":2664,"target":1695},{"edgeType":"calls","source":1253,"target":1301},{"edgeType":"contains","source":119,"target":2640},{"edgeType":"contains","source":1866,"target":1867},{"edgeType":"imports","source":427,"target":430},{"edgeType":"calls","source":1674,"target":670},{"edgeType":"contains","source":457,"target":2204},{"edgeType":"imports","source":980,"target":992},{"edgeType":"contains","source":2551,"target":2562},{"edgeType":"contains","source":8,"target":1592},{"edgeType":"contains","source":119,"target":1322},{"edgeType":"contains","source":305,"target":313},{"edgeType":"calls","source":1994,"target":2117},{"edgeType":"calls","source":1558,"target":570},{"edgeType":"calls","source":2150,"target":2034},{"edgeType":"calls","source":1426,"target":170},{"edgeType":"calls","source":2171,"target":326},{"edgeType":"contains","source":1222,"target":2008},{"edgeType":"contains","source":282,"target":762},{"edgeType":"contains","source":283,"target":731},{"edgeType":"calls","source":2791,"target":2775},{"edgeType":"contains","source":74,"target":75},{"edgeType":"calls","source":1942,"target":1086},{"edgeType":"contains","source":1868,"target":2066},{"edgeType":"calls","source":1253,"target":1304},{"edgeType":"calls","source":1715,"target":2045},{"edgeType":"contains","source":76,"target":1070},{"edgeType":"calls","source":2228,"target":2259},{"edgeType":"calls","source":970,"target":1093},{"edgeType":"contains","source":450,"target":574},{"edgeType":"calls","source":1237,"target":479},{"edgeType":"calls","source":2319,"target":2345},{"edgeType":"contains","source":221,"target":274},{"edgeType":"calls","source":1438,"target":326},{"edgeType":"contains","source":346,"target":363},{"edgeType":"calls","source":2611,"target":1485},{"edgeType":"calls","source":1826,"target":982},{"edgeType":"calls","source":1715,"target":195},{"edgeType":"imports","source":1447,"target":782},{"edgeType":"calls","source":2150,"target":2035},{"edgeType":"calls","source":1937,"target":976},{"edgeType":"contains","source":307,"target":2100},{"edgeType":"calls","source":2083,"target":678},{"edgeType":"calls","source":1253,"target":1303},{"edgeType":"contains","source":283,"target":729},{"edgeType":"contains","source":1873,"target":1912},{"edgeType":"contains","source":1868,"target":2067},{"edgeType":"calls","source":1942,"target":1085},{"edgeType":"contains","source":119,"target":2642},{"edgeType":"calls","source":1861,"target":689},{"edgeType":"calls","source":1715,"target":2044},{"edgeType":"imports","source":131,"target":91},{"edgeType":"contains","source":221,"target":273},{"edgeType":"contains","source":346,"target":362},{"edgeType":"calls","source":2600,"target":502},{"edgeType":"calls","source":1877,"target":1774},{"edgeType":"calls","source":1340,"target":187},{"edgeType":"contains","source":980,"target":2645},{"edgeType":"calls","source":2168,"target":681},{"edgeType":"contains","source":293,"target":1744},{"edgeType":"contains","source":307,"target":2103},{"edgeType":"contains","source":282,"target":764},{"edgeType":"contains","source":283,"target":733},{"edgeType":"calls","source":970,"target":1086},{"edgeType":"contains","source":197,"target":227},{"edgeType":"contains","source":457,"target":2209},{"edgeType":"calls","source":2646,"target":662},{"edgeType":"contains","source":1866,"target":1870},{"edgeType":"contains","source":8,"target":9},{"edgeType":"calls","source":2672,"target":2763},{"edgeType":"contains","source":76,"target":1072},{"edgeType":"contains","source":1472,"target":1928},{"edgeType":"contains","source":450,"target":576},{"edgeType":"contains","source":221,"target":276},{"edgeType":"contains","source":352,"target":2293},{"edgeType":"contains","source":147,"target":192},{"edgeType":"calls","source":1932,"target":1918},{"edgeType":"contains","source":346,"target":365},{"edgeType":"calls","source":1403,"target":1404},{"edgeType":"contains","source":113,"target":452},{"edgeType":"calls","source":1337,"target":1336},{"edgeType":"calls","source":1340,"target":186},{"edgeType":"calls","source":2018,"target":573},{"edgeType":"contains","source":293,"target":1743},{"edgeType":"calls","source":1537,"target":1478},{"edgeType":"imports","source":1234,"target":1323},{"edgeType":"calls","source":2600,"target":2617},{"edgeType":"calls","source":970,"target":1085},{"edgeType":"contains","source":307,"target":2102},{"edgeType":"contains","source":76,"target":1071},{"edgeType":"contains","source":1794,"target":1989},{"edgeType":"contains","source":1651,"target":1665},{"edgeType":"contains","source":221,"target":275},{"edgeType":"calls","source":1312,"target":1318},{"edgeType":"contains","source":1868,"target":2073},{"edgeType":"calls","source":2840,"target":2841},{"edgeType":"contains","source":293,"target":1746},{"edgeType":"contains","source":966,"target":967},{"edgeType":"calls","source":1877,"target":1776},{"edgeType":"contains","source":282,"target":766},{"edgeType":"contains","source":283,"target":735},{"edgeType":"calls","source":2083,"target":675},{"edgeType":"contains","source":450,"target":579},{"edgeType":"calls","source":1942,"target":1082},{"edgeType":"calls","source":970,"target":1089},{"edgeType":"contains","source":221,"target":278},{"edgeType":"contains","source":346,"target":367},{"edgeType":"imports","source":1447,"target":1853},{"edgeType":"calls","source":2840,"target":2838},{"edgeType":"contains","source":1670,"target":1866},{"edgeType":"calls","source":1426,"target":958},{"edgeType":"calls","source":1243,"target":288},{"edgeType":"calls","source":1661,"target":1336},{"edgeType":"contains","source":113,"target":454},{"edgeType":"calls","source":2480,"target":1314},{"edgeType":"calls","source":665,"target":236},{"edgeType":"contains","source":307,"target":2104},{"edgeType":"contains","source":858,"target":1671},{"edgeType":"contains","source":972,"target":1044},{"edgeType":"contains","source":160,"target":1376},{"edgeType":"calls","source":970,"target":1087},{"edgeType":"contains","source":8,"target":10},{"edgeType":"contains","source":160,"target":1375},{"edgeType":"calls","source":970,"target":1088},{"edgeType":"calls","source":2672,"target":2762},{"edgeType":"calls","source":2813,"target":2355},{"edgeType":"contains","source":76,"target":1073},{"edgeType":"contains","source":1794,"target":1987},{"edgeType":"contains","source":221,"target":277},{"edgeType":"contains","source":1111,"target":1491},{"edgeType":"calls","source":2495,"target":1114},{"edgeType":"contains","source":1335,"target":1686},{"edgeType":"calls","source":461,"target":477},{"edgeType":"calls","source":2018,"target":570},{"edgeType":"calls","source":2189,"target":2140},{"edgeType":"contains","source":282,"target":768},{"edgeType":"contains","source":283,"target":737},{"edgeType":"contains","source":972,"target":1047},{"edgeType":"contains","source":126,"target":1111},{"edgeType":"calls","source":970,"target":1082},{"edgeType":"contains","source":1969,"target":1323},{"edgeType":"calls","source":2175,"target":196},{"edgeType":"calls","source":1989,"target":1997},{"edgeType":"contains","source":221,"target":280},{"edgeType":"calls","source":1916,"target":296},{"edgeType":"contains","source":457,"target":2213},{"edgeType":"contains","source":96,"target":456},{"edgeType":"calls","source":1352,"target":1396},{"edgeType":"calls","source":1315,"target":429},{"edgeType":"calls","source":1311,"target":288},{"edgeType":"calls","source":2107,"target":1776},{"edgeType":"calls","source":1171,"target":664},{"edgeType":"calls","source":2319,"target":2339},{"edgeType":"contains","source":293,"target":1747},{"edgeType":"contains","source":980,"target":2648},{"edgeType":"calls","source":2168,"target":678},{"edgeType":"contains","source":450,"target":580},{"edgeType":"calls","source":1715,"target":184},{"edgeType":"calls","source":2600,"target":499},{"edgeType":"contains","source":119,"target":2649},{"edgeType":"calls","source":2172,"target":290},{"edgeType":"calls","source":2448,"target":1776},{"edgeType":"contains","source":1482,"target":1623},{"edgeType":"contains","source":430,"target":1992},{"edgeType":"calls","source":2840,"target":2837},{"edgeType":"contains","source":221,"target":279},{"edgeType":"contains","source":346,"target":368},{"edgeType":"calls","source":1095,"target":1170},{"edgeType":"calls","source":1878,"target":680},{"edgeType":"calls","source":1312,"target":1317},{"edgeType":"calls","source":2018,"target":572},{"edgeType":"contains","source":282,"target":770},{"edgeType":"calls","source":2448,"target":451},{"edgeType":"calls","source":2354,"target":194},{"edgeType":"calls","source":2672,"target":2756},{"edgeType":"calls","source":2154,"target":2166},{"edgeType":"calls","source":2168,"target":675},{"edgeType":"calls","source":1846,"target":1940},{"edgeType":"calls","source":970,"target":1084},{"edgeType":"calls","source":1188,"target":669},{"edgeType":"calls","source":2244,"target":2019},{"edgeType":"contains","source":1482,"target":1620},{"edgeType":"contains","source":1651,"target":1666},{"edgeType":"calls","source":1715,"target":187},{"edgeType":"calls","source":2658,"target":2662},{"edgeType":"contains","source":1873,"target":1919},{"edgeType":"calls","source":2815,"target":2816},{"edgeType":"calls","source":2107,"target":1774},{"edgeType":"calls","source":2083,"target":670},{"edgeType":"calls","source":2657,"target":2165},{"edgeType":"contains","source":1651,"target":1667},{"edgeType":"contains","source":119,"target":2651},{"edgeType":"calls","source":970,"target":1083},{"edgeType":"calls","source":1340,"target":184},{"edgeType":"calls","source":2228,"target":666},{"edgeType":"contains","source":972,"target":1048},{"edgeType":"contains","source":450,"target":582},{"edgeType":"calls","source":2175,"target":195},{"edgeType":"calls","source":2175,"target":1252},{"edgeType":"calls","source":2199,"target":508},{"edgeType":"calls","source":2448,"target":1774},{"edgeType":"contains","source":221,"target":281},{"edgeType":"calls","source":1715,"target":186},{"edgeType":"contains","source":346,"target":370},{"edgeType":"contains","source":1668,"target":1669},{"edgeType":"calls","source":2729,"target":462},{"edgeType":"contains","source":1185,"target":1051},{"edgeType":"contains","source":92,"target":1638},{"edgeType":"contains","source":858,"target":882},{"edgeType":"contains","source":1052,"target":1181},{"edgeType":"contains","source":1501,"target":2325},{"edgeType":"contains","source":2478,"target":2428},{"edgeType":"contains","source":283,"target":708},{"edgeType":"calls","source":2219,"target":2230},{"edgeType":"contains","source":160,"target":1350},{"edgeType":"contains","source":119,"target":2621},{"edgeType":"contains","source":87,"target":1234},{"edgeType":"calls","source":1426,"target":1443},{"edgeType":"contains","source":1472,"target":1903},{"edgeType":"calls","source":2433,"target":2467},{"edgeType":"contains","source":2446,"target":2627},{"edgeType":"contains","source":1411,"target":1416},{"edgeType":"imports","source":1854,"target":1435},{"edgeType":"calls","source":2150,"target":670},{"edgeType":"calls","source":2566,"target":194},{"edgeType":"imports","source":1234,"target":836},{"edgeType":"contains","source":1078,"target":2488},{"edgeType":"contains","source":1103,"target":1713},{"edgeType":"contains","source":282,"target":738},{"edgeType":"calls","source":1038,"target":1579},{"edgeType":"contains","source":119,"target":2620},{"edgeType":"imports","source":1234,"target":2420},{"edgeType":"contains","source":1472,"target":1904},{"edgeType":"calls","source":1633,"target":1632},{"edgeType":"contains","source":65,"target":66},{"edgeType":"calls","source":2600,"target":1255},{"edgeType":"calls","source":1426,"target":1442},{"edgeType":"calls","source":2319,"target":1774},{"edgeType":"contains","source":1721,"target":1849},{"edgeType":"calls","source":2880,"target":2881},{"edgeType":"contains","source":121,"target":2029},{"edgeType":"contains","source":165,"target":665},{"edgeType":"calls","source":2652,"target":700},{"edgeType":"contains","source":980,"target":1297},{"edgeType":"calls","source":2764,"target":2774},{"edgeType":"contains","source":1111,"target":1468},{"edgeType":"contains","source":283,"target":710},{"edgeType":"contains","source":478,"target":479},{"edgeType":"calls","source":1073,"target":1290},{"edgeType":"calls","source":2652,"target":697},{"edgeType":"imports","source":1113,"target":91},{"edgeType":"calls","source":2341,"target":296},{"edgeType":"contains","source":352,"target":2270},{"edgeType":"contains","source":1475,"target":1544},{"edgeType":"contains","source":1080,"target":1107},{"edgeType":"calls","source":1874,"target":1827},{"edgeType":"calls","source":1715,"target":1735},{"edgeType":"contains","source":1501,"target":1795},{"edgeType":"contains","source":1316,"target":2245},{"edgeType":"contains","source":1378,"target":1380},{"edgeType":"contains","source":180,"target":996},{"edgeType":"contains","source":282,"target":740},{"edgeType":"contains","source":1111,"target":1467},{"edgeType":"calls","source":1038,"target":1581},{"edgeType":"contains","source":119,"target":2622},{"edgeType":"contains","source":6,"target":575},{"edgeType":"calls","source":1073,"target":1289},{"edgeType":"calls","source":1952,"target":994},{"edgeType":"contains","source":255,"target":256},{"edgeType":"contains","source":352,"target":2269},{"edgeType":"contains","source":1472,"target":1902},{"edgeType":"calls","source":1809,"target":670},{"edgeType":"imports","source":1447,"target":836},{"edgeType":"calls","source":946,"target":205},{"edgeType":"contains","source":1080,"target":1106},{"edgeType":"contains","source":180,"target":1259},{"edgeType":"contains","source":293,"target":1720},{"edgeType":"contains","source":1794,"target":1962},{"edgeType":"contains","source":283,"target":712},{"edgeType":"contains","source":282,"target":743},{"edgeType":"calls","source":2893,"target":1944},{"edgeType":"contains","source":1078,"target":2493},{"edgeType":"calls","source":2764,"target":2772},{"edgeType":"calls","source":1960,"target":1798},{"edgeType":"calls","source":1429,"target":1611},{"edgeType":"calls","source":1038,"target":1576},{"edgeType":"calls","source":1930,"target":878},{"edgeType":"calls","source":2246,"target":1125},{"edgeType":"calls","source":2839,"target":976},{"edgeType":"calls","source":2433,"target":2199},{"edgeType":"calls","source":1006,"target":982},{"edgeType":"calls","source":1817,"target":681},{"edgeType":"calls","source":2358,"target":296},{"edgeType":"contains","source":283,"target":711},{"edgeType":"calls","source":1952,"target":988},{"edgeType":"calls","source":2893,"target":1945},{"edgeType":"contains","source":119,"target":2624},{"edgeType":"calls","source":2764,"target":2773},{"edgeType":"calls","source":1988,"target":1986},{"edgeType":"calls","source":1038,"target":1575},{"edgeType":"calls","source":1963,"target":1968},{"edgeType":"contains","source":1794,"target":2761},{"edgeType":"calls","source":1074,"target":194},{"edgeType":"contains","source":25,"target":253},{"edgeType":"calls","source":1377,"target":1107},{"edgeType":"calls","source":1429,"target":1609},{"edgeType":"contains","source":2446,"target":2632},{"edgeType":"contains","source":180,"target":204},{"edgeType":"contains","source":126,"target":293},{"edgeType":"calls","source":1888,"target":593},{"edgeType":"contains","source":25,"target":517},{"edgeType":"calls","source":1565,"target":1357},{"edgeType":"contains","source":283,"target":714},{"edgeType":"contains","source":282,"target":745},{"edgeType":"contains","source":1625,"target":1654},{"edgeType":"contains","source":858,"target":859},{"edgeType":"calls","source":2764,"target":2770},{"edgeType":"contains","source":430,"target":121},{"edgeType":"contains","source":457,"target":2191},{"edgeType":"contains","source":1836,"target":134},{"edgeType":"contains","source":1472,"target":1905},{"edgeType":"contains","source":2493,"target":2494},{"edgeType":"calls","source":1426,"target":1441},{"edgeType":"calls","source":1040,"target":194},{"edgeType":"contains","source":1758,"target":1760},{"edgeType":"calls","source":2363,"target":667},{"edgeType":"contains","source":1316,"target":2249},{"edgeType":"calls","source":1006,"target":984},{"edgeType":"calls","source":2468,"target":2433},{"edgeType":"contains","source":283,"target":713},{"edgeType":"calls","source":2651,"target":1253},{"edgeType":"contains","source":197,"target":208},{"edgeType":"contains","source":119,"target":2626},{"edgeType":"calls","source":2764,"target":2771},{"edgeType":"calls","source":179,"target":194},{"edgeType":"contains","source":1,"target":470},{"edgeType":"contains","source":77,"target":1285},{"edgeType":"calls","source":1038,"target":1577},{"edgeType":"contains","source":298,"target":1041},{"edgeType":"contains","source":1472,"target":1906},{"edgeType":"contains","source":2493,"target":2495},{"edgeType":"calls","source":1426,"target":1440},{"edgeType":"contains","source":1794,"target":2759},{"edgeType":"calls","source":2246,"target":1124},{"edgeType":"contains","source":1335,"target":1661},{"edgeType":"contains","source":303,"target":1414},{"edgeType":"calls","source":2084,"target":1918},{"edgeType":"calls","source":2097,"target":194},{"edgeType":"contains","source":119,"target":2629},{"edgeType":"imports","source":303,"target":107},{"edgeType":"calls","source":1833,"target":710},{"edgeType":"calls","source":1189,"target":326},{"edgeType":"contains","source":1794,"target":1971},{"edgeType":"contains","source":1222,"target":1469},{"edgeType":"calls","source":2433,"target":1930},{"edgeType":"calls","source":2888,"target":2359},{"edgeType":"contains","source":2551,"target":2552},{"edgeType":"calls","source":2448,"target":1201},{"edgeType":"imports","source":1234,"target":1371},{"edgeType":"calls","source":2336,"target":1238},{"edgeType":"contains","source":1335,"target":1402},{"edgeType":"contains","source":283,"target":716},{"edgeType":"contains","source":119,"target":2628},{"edgeType":"calls","source":1016,"target":667},{"edgeType":"contains","source":197,"target":210},{"edgeType":"calls","source":213,"target":455},{"edgeType":"contains","source":1222,"target":1470},{"edgeType":"contains","source":1113,"target":2468},{"edgeType":"calls","source":1930,"target":1930},{"edgeType":"contains","source":2446,"target":2636},{"edgeType":"contains","source":1411,"target":1425},{"edgeType":"calls","source":2448,"target":1202},{"edgeType":"imports","source":1543,"target":513},{"edgeType":"calls","source":2888,"target":2889},{"edgeType":"calls","source":2764,"target":2769},{"edgeType":"contains","source":1625,"target":1662},{"edgeType":"contains","source":1641,"target":109},{"edgeType":"contains","source":282,"target":746},{"edgeType":"contains","source":283,"target":715},{"edgeType":"contains","source":457,"target":2195},{"edgeType":"contains","source":76,"target":1057},{"edgeType":"contains","source":96,"target":1494},{"edgeType":"contains","source":470,"target":471},{"edgeType":"contains","source":87,"target":980},{"edgeType":"calls","source":2548,"target":2591},{"edgeType":"calls","source":1038,"target":1574},{"edgeType":"calls","source":1952,"target":194},{"edgeType":"calls","source":1011,"target":296},{"edgeType":"contains","source":1031,"target":1049},{"edgeType":"contains","source":304,"target":1388},{"edgeType":"calls","source":1429,"target":1608},{"edgeType":"contains","source":1543,"target":1558},{"edgeType":"contains","source":2446,"target":2633},{"edgeType":"calls","source":2812,"target":2335},{"edgeType":"calls","source":1888,"target":592},{"edgeType":"contains","source":1625,"target":1659},{"edgeType":"calls","source":1426,"target":1437},{"edgeType":"contains","source":283,"target":718},{"edgeType":"calls","source":1092,"target":1485},{"edgeType":"calls","source":2764,"target":1709},{"edgeType":"calls","source":1565,"target":1356},{"edgeType":"contains","source":119,"target":2631},{"edgeType":"contains","source":1335,"target":1400},{"edgeType":"contains","source":119,"target":2630},{"edgeType":"calls","source":2189,"target":508},{"edgeType":"contains","source":2428,"target":1343},{"edgeType":"calls","source":2548,"target":2592},{"edgeType":"calls","source":1038,"target":1573},{"edgeType":"calls","source":2448,"target":1200},{"edgeType":"contains","source":2446,"target":2634},{"edgeType":"contains","source":1411,"target":1423},{"edgeType":"calls","source":2329,"target":2775},{"edgeType":"calls","source":1817,"target":678},{"edgeType":"contains","source":352,"target":1749},{"edgeType":"contains","source":25,"target":1316},{"edgeType":"contains","source":1625,"target":1660},{"edgeType":"contains","source":283,"target":717},{"edgeType":"contains","source":282,"target":748},{"edgeType":"imports","source":1854,"target":119},{"edgeType":"calls","source":2196,"target":288},{"edgeType":"calls","source":2189,"target":505},{"edgeType":"calls","source":1159,"target":195},{"edgeType":"contains","source":148,"target":149},{"edgeType":"calls","source":2167,"target":1980},{"edgeType":"calls","source":1685,"target":1858},{"edgeType":"calls","source":1590,"target":1632},{"edgeType":"calls","source":1079,"target":296},{"edgeType":"contains","source":283,"target":720},{"edgeType":"contains","source":282,"target":751},{"edgeType":"calls","source":2627,"target":669},{"edgeType":"contains","source":65,"target":79},{"edgeType":"contains","source":15,"target":42},{"edgeType":"calls","source":2548,"target":2590},{"edgeType":"contains","source":11,"target":1223},{"edgeType":"calls","source":2424,"target":356},{"edgeType":"calls","source":2448,"target":669},{"edgeType":"calls","source":2167,"target":1981},{"edgeType":"calls","source":2353,"target":1500},{"edgeType":"contains","source":181,"target":182},{"edgeType":"contains","source":101,"target":1605},{"edgeType":"contains","source":293,"target":1730},{"edgeType":"calls","source":1685,"target":1857},{"edgeType":"calls","source":1263,"target":669},{"edgeType":"calls","source":1598,"target":326},{"edgeType":"calls","source":1517,"target":194},{"edgeType":"contains","source":283,"target":719},{"edgeType":"contains","source":450,"target":563},{"edgeType":"contains","source":1651,"target":1653},{"edgeType":"calls","source":1596,"target":1709},{"edgeType":"calls","source":2764,"target":1708},{"edgeType":"calls","source":1833,"target":708},{"edgeType":"calls","source":1824,"target":194},{"edgeType":"contains","source":2551,"target":2554},{"edgeType":"imports","source":1234,"target":2423},{"edgeType":"calls","source":2189,"target":503},{"edgeType":"contains","source":180,"target":216},{"edgeType":"contains","source":1447,"target":2424},{"edgeType":"calls","source":1923,"target":296},{"edgeType":"calls","source":2429,"target":1255},{"edgeType":"calls","source":2363,"target":1980},{"edgeType":"calls","source":1817,"target":675},{"edgeType":"contains","source":76,"target":1326},{"edgeType":"contains","source":148,"target":151},{"edgeType":"calls","source":2118,"target":326},{"edgeType":"calls","source":2541,"target":690},{"edgeType":"contains","source":282,"target":753},{"edgeType":"contains","source":283,"target":722},{"edgeType":"contains","source":119,"target":2635},{"edgeType":"imports","source":47,"target":109},{"edgeType":"calls","source":2818,"target":1088},{"edgeType":"contains","source":1625,"target":1663},{"edgeType":"contains","source":1482,"target":1604},{"edgeType":"contains","source":1472,"target":1914},{"edgeType":"calls","source":2839,"target":2816},{"edgeType":"calls","source":1159,"target":196},{"edgeType":"contains","source":1411,"target":1427},{"edgeType":"contains","source":2551,"target":2555},{"edgeType":"calls","source":2167,"target":1979},{"edgeType":"calls","source":461,"target":429},{"edgeType":"calls","source":2194,"target":2199},{"edgeType":"contains","source":148,"target":150},{"edgeType":"calls","source":2363,"target":1981},{"edgeType":"contains","source":1684,"target":1685},{"edgeType":"contains","source":450,"target":565},{"edgeType":"contains","source":88,"target":160},{"edgeType":"contains","source":25,"target":263},{"edgeType":"calls","source":2818,"target":1089},{"edgeType":"calls","source":1402,"target":326},{"edgeType":"calls","source":1685,"target":1859},{"edgeType":"contains","source":64,"target":111},{"edgeType":"calls","source":2812,"target":2332},{"edgeType":"contains","source":352,"target":2252},{"edgeType":"contains","source":219,"target":297},{"edgeType":"calls","source":2437,"target":2359},{"edgeType":"calls","source":2600,"target":477},{"edgeType":"calls","source":2352,"target":502},{"edgeType":"calls","source":2465,"target":1227},{"edgeType":"imports","source":1543,"target":1546},{"edgeType":"contains","source":1392,"target":1724},{"edgeType":"calls","source":1757,"target":976},{"edgeType":"contains","source":972,"target":1001},{"edgeType":"calls","source":2840,"target":2816},{"edgeType":"contains","source":880,"target":946},{"edgeType":"contains","source":1111,"target":1184},{"edgeType":"calls","source":1936,"target":976},{"edgeType":"contains","source":1,"target":447},{"edgeType":"contains","source":1316,"target":2231},{"edgeType":"contains","source":1794,"target":1947},{"edgeType":"calls","source":2460,"target":326},{"edgeType":"calls","source":2465,"target":1228},{"edgeType":"contains","source":81,"target":82},{"edgeType":"contains","source":1078,"target":2471},{"edgeType":"contains","source":201,"target":325},{"edgeType":"contains","source":147,"target":942},{"edgeType":"calls","source":2572,"target":290},{"edgeType":"calls","source":1879,"target":364},{"edgeType":"calls","source":1528,"target":675},{"edgeType":"contains","source":2137,"target":2149},{"edgeType":"calls","source":1633,"target":1648},{"edgeType":"contains","source":969,"target":1093},{"edgeType":"contains","source":858,"target":1631},{"edgeType":"calls","source":2087,"target":2108},{"edgeType":"contains","source":972,"target":1004},{"edgeType":"calls","source":2413,"target":194},{"edgeType":"calls","source":2600,"target":475},{"edgeType":"contains","source":87,"target":427},{"edgeType":"calls","source":951,"target":1124},{"edgeType":"calls","source":2465,"target":1225},{"edgeType":"contains","source":1836,"target":1963},{"edgeType":"calls","source":1322,"target":194},{"edgeType":"calls","source":2253,"target":662},{"edgeType":"contains","source":201,"target":329},{"edgeType":"calls","source":2029,"target":1267},{"edgeType":"contains","source":1625,"target":1634},{"edgeType":"contains","source":201,"target":328},{"edgeType":"calls","source":1528,"target":678},{"edgeType":"calls","source":1344,"target":1361},{"edgeType":"calls","source":134,"target":290},{"edgeType":"imports","source":307,"target":1013},{"edgeType":"contains","source":255,"target":1032},{"edgeType":"calls","source":1878,"target":662},{"edgeType":"calls","source":2465,"target":1226},{"edgeType":"calls","source":1740,"target":976},{"edgeType":"contains","source":1176,"target":2342},{"edgeType":"calls","source":2029,"target":1266},{"edgeType":"contains","source":1316,"target":2229},{"edgeType":"contains","source":201,"target":327},{"edgeType":"contains","source":15,"target":16},{"edgeType":"contains","source":282,"target":723},{"edgeType":"contains","source":980,"target":2604},{"edgeType":"contains","source":463,"target":1190},{"edgeType":"contains","source":1501,"target":1784},{"edgeType":"calls","source":1426,"target":1456},{"edgeType":"contains","source":972,"target":1006},{"edgeType":"contains","source":1794,"target":2743},{"edgeType":"contains","source":2446,"target":2615},{"edgeType":"contains","source":304,"target":1366},{"edgeType":"contains","source":201,"target":331},{"edgeType":"contains","source":137,"target":200},{"edgeType":"contains","source":202,"target":1092},{"edgeType":"imports","source":1836,"target":123},{"edgeType":"calls","source":2350,"target":296},{"edgeType":"calls","source":2159,"target":1196},{"edgeType":"contains","source":2137,"target":2152},{"edgeType":"calls","source":1264,"target":664},{"edgeType":"contains","source":87,"target":165},{"edgeType":"contains","source":1178,"target":697},{"edgeType":"calls","source":2600,"target":474},{"edgeType":"contains","source":304,"target":1365},{"edgeType":"calls","source":986,"target":296},{"edgeType":"contains","source":1316,"target":2235},{"edgeType":"calls","source":2026,"target":296},{"edgeType":"calls","source":2473,"target":976},{"edgeType":"contains","source":201,"target":330},{"edgeType":"calls","source":2658,"target":2640},{"edgeType":"calls","source":1426,"target":1455},{"edgeType":"calls","source":1808,"target":976},{"edgeType":"calls","source":2352,"target":499},{"edgeType":"contains","source":1335,"target":1382},{"edgeType":"calls","source":1968,"target":508},{"edgeType":"contains","source":282,"target":725},{"edgeType":"contains","source":65,"target":1639},{"edgeType":"calls","source":2091,"target":1191},{"edgeType":"calls","source":1846,"target":326},{"edgeType":"contains","source":1794,"target":2480},{"edgeType":"contains","source":1178,"target":700},{"edgeType":"contains","source":1414,"target":1572},{"edgeType":"calls","source":2199,"target":1539},{"edgeType":"calls","source":1912,"target":662},{"edgeType":"contains","source":304,"target":311},{"edgeType":"contains","source":201,"target":333},{"edgeType":"contains","source":1,"target":190},{"edgeType":"contains","source":282,"target":728},{"edgeType":"contains","source":139,"target":141},{"edgeType":"contains","source":1873,"target":1878},{"edgeType":"calls","source":1812,"target":326},{"edgeType":"contains","source":114,"target":123},{"edgeType":"contains","source":1078,"target":2478},{"edgeType":"calls","source":1953,"target":976},{"edgeType":"contains","source":1472,"target":1889},{"edgeType":"contains","source":2446,"target":2614},{"edgeType":"calls","source":2764,"target":673},{"edgeType":"contains","source":126,"target":1335},{"edgeType":"calls","source":2175,"target":170},{"edgeType":"contains","source":1316,"target":2233},{"edgeType":"contains","source":201,"target":332},{"edgeType":"contains","source":1794,"target":1949},{"edgeType":"contains","source":114,"target":1972},{"edgeType":"calls","source":2548,"target":2613},{"edgeType":"calls","source":2483,"target":664},{"edgeType":"calls","source":1740,"target":1500},{"edgeType":"imports","source":1447,"target":1080},{"edgeType":"imports","source":1447,"target":2137},{"edgeType":"calls","source":2764,"target":1463},{"edgeType":"calls","source":1961,"target":194},{"edgeType":"contains","source":119,"target":2084},{"edgeType":"calls","source":1824,"target":477},{"edgeType":"calls","source":2316,"target":288},{"edgeType":"contains","source":1316,"target":2238},{"edgeType":"calls","source":1535,"target":451},{"edgeType":"contains","source":1794,"target":2483},{"edgeType":"calls","source":2572,"target":1601},{"edgeType":"contains","source":201,"target":335},{"edgeType":"calls","source":2764,"target":670},{"edgeType":"contains","source":96,"target":154},{"edgeType":"contains","source":1335,"target":1385},{"edgeType":"calls","source":2677,"target":1253},{"edgeType":"calls","source":2174,"target":1255},{"edgeType":"contains","source":882,"target":893},{"edgeType":"contains","source":40,"target":41},{"edgeType":"calls","source":1968,"target":505},{"edgeType":"calls","source":2572,"target":1602},{"edgeType":"calls","source":1253,"target":1265},{"edgeType":"calls","source":1345,"target":1320},{"edgeType":"calls","source":2839,"target":2838},{"edgeType":"calls","source":1038,"target":1588},{"edgeType":"calls","source":1038,"target":1587},{"edgeType":"calls","source":2764,"target":1464},{"edgeType":"calls","source":236,"target":287},{"edgeType":"calls","source":1596,"target":1202},{"edgeType":"calls","source":1596,"target":673},{"edgeType":"contains","source":201,"target":334},{"edgeType":"calls","source":1426,"target":1451},{"edgeType":"calls","source":1299,"target":1424},{"edgeType":"contains","source":1794,"target":2748},{"edgeType":"contains","source":282,"target":730},{"edgeType":"calls","source":1100,"target":194},{"edgeType":"calls","source":2072,"target":1244},{"edgeType":"calls","source":1092,"target":1499},{"edgeType":"contains","source":2563,"target":2428},{"edgeType":"calls","source":1426,"target":1186},{"edgeType":"contains","source":1113,"target":2187},{"edgeType":"contains","source":1472,"target":1896},{"edgeType":"calls","source":1596,"target":1201},{"edgeType":"contains","source":1501,"target":1790},{"edgeType":"calls","source":1927,"target":982},{"edgeType":"contains","source":1475,"target":1539},{"edgeType":"calls","source":141,"target":326},{"edgeType":"contains","source":121,"target":2024},{"edgeType":"contains","source":1794,"target":2745},{"edgeType":"imports","source":1447,"target":1621},{"edgeType":"contains","source":1721,"target":2101},{"edgeType":"contains","source":1316,"target":2236},{"edgeType":"calls","source":1092,"target":1502},{"edgeType":"calls","source":1785,"target":1688},{"edgeType":"contains","source":1335,"target":1383},{"edgeType":"contains","source":1111,"target":1459},{"edgeType":"contains","source":202,"target":1627},{"edgeType":"calls","source":1299,"target":1426},{"edgeType":"contains","source":1316,"target":2237},{"edgeType":"calls","source":1340,"target":948},{"edgeType":"contains","source":282,"target":732},{"edgeType":"contains","source":1335,"target":1384},{"edgeType":"imports","source":114,"target":1985},{"edgeType":"contains","source":6,"target":39},{"edgeType":"contains","source":1116,"target":2096},{"edgeType":"contains","source":352,"target":2261},{"edgeType":"calls","source":1927,"target":984},{"edgeType":"calls","source":2839,"target":2837},{"edgeType":"calls","source":1038,"target":1589},{"edgeType":"calls","source":2031,"target":1191},{"edgeType":"calls","source":1038,"target":1584},{"edgeType":"contains","source":119,"target":1824},{"edgeType":"calls","source":1817,"target":690},{"edgeType":"calls","source":1269,"target":1294},{"edgeType":"contains","source":446,"target":672},{"edgeType":"contains","source":1794,"target":2751},{"edgeType":"calls","source":1092,"target":1495},{"edgeType":"contains","source":352,"target":2264},{"edgeType":"contains","source":2446,"target":2623},{"edgeType":"contains","source":1411,"target":1412},{"edgeType":"calls","source":164,"target":667},{"edgeType":"contains","source":1475,"target":1542},{"edgeType":"contains","source":1316,"target":2243},{"edgeType":"contains","source":1625,"target":1649},{"edgeType":"calls","source":1038,"target":1583},{"edgeType":"calls","source":1595,"target":436},{"edgeType":"contains","source":1435,"target":1461},{"edgeType":"contains","source":154,"target":209},{"edgeType":"contains","source":1794,"target":2752},{"edgeType":"calls","source":1073,"target":1291},{"edgeType":"contains","source":282,"target":734},{"edgeType":"contains","source":197,"target":198},{"edgeType":"calls","source":1686,"target":1314},{"edgeType":"contains","source":11,"target":943},{"edgeType":"contains","source":1794,"target":2224},{"edgeType":"contains","source":121,"target":2025},{"edgeType":"calls","source":1824,"target":475},{"edgeType":"calls","source":1038,"target":1586},{"edgeType":"contains","source":1316,"target":2240},{"edgeType":"calls","source":2228,"target":2217},{"edgeType":"calls","source":1528,"target":666},{"edgeType":"contains","source":154,"target":212},{"edgeType":"calls","source":1426,"target":1450},{"edgeType":"contains","source":1794,"target":2749},{"edgeType":"calls","source":1092,"target":1498},{"edgeType":"calls","source":1092,"target":1497},{"edgeType":"calls","source":1968,"target":503},{"edgeType":"calls","source":1470,"target":878},{"edgeType":"calls","source":2890,"target":194},{"edgeType":"contains","source":352,"target":2266},{"edgeType":"calls","source":2370,"target":194},{"edgeType":"contains","source":1113,"target":2194},{"edgeType":"calls","source":1596,"target":1200},{"edgeType":"contains","source":1475,"target":1540},{"edgeType":"calls","source":1824,"target":474},{"edgeType":"contains","source":293,"target":1716},{"edgeType":"calls","source":1038,"target":1585},{"edgeType":"imports","source":1113,"target":1930},{"edgeType":"contains","source":8,"target":1566},{"edgeType":"contains","source":980,"target":2617},{"edgeType":"contains","source":282,"target":736},{"edgeType":"calls","source":1426,"target":1449},{"edgeType":"contains","source":1794,"target":2750},{"edgeType":"contains","source":119,"target":2618},{"edgeType":"calls","source":129,"target":167},{"edgeType":"contains","source":430,"target":1961},{"edgeType":"contains","source":981,"target":1000},{"edgeType":"calls","source":2145,"target":2149},{"edgeType":"calls","source":1092,"target":1496},{"edgeType":"calls","source":2600,"target":1257},{"edgeType":"calls","source":2631,"target":296},{"edgeType":"contains","source":1794,"target":1958},{"edgeType":"contains","source":457,"target":2181},{"edgeType":"calls","source":2319,"target":1776},{"edgeType":"contains","source":980,"target":1295},{"edgeType":"contains","source":1475,"target":1541},{"edgeType":"calls","source":2792,"target":326},{"edgeType":"calls","source":1470,"target":1500},{"edgeType":"calls","source":1312,"target":320},{"edgeType":"contains","source":147,"target":927},{"edgeType":"contains","source":1721,"target":1814},{"edgeType":"contains","source":1335,"target":1360},{"edgeType":"contains","source":1411,"target":1911},{"edgeType":"calls","source":2764,"target":1025},{"edgeType":"contains","source":119,"target":2588},{"edgeType":"contains","source":298,"target":1003},{"edgeType":"calls","source":1040,"target":296},{"edgeType":"contains","source":1,"target":960},{"edgeType":"contains","source":1428,"target":327},{"edgeType":"contains","source":972,"target":985},{"edgeType":"contains","source":1116,"target":2863},{"edgeType":"contains","source":457,"target":2151},{"edgeType":"calls","source":2764,"target":1026},{"edgeType":"contains","source":25,"target":1538},{"edgeType":"contains","source":25,"target":481},{"edgeType":"contains","source":1178,"target":1205},{"edgeType":"contains","source":1316,"target":2214},{"edgeType":"calls","source":1952,"target":563},{"edgeType":"calls","source":1312,"target":319},{"edgeType":"calls","source":1122,"target":1188},{"edgeType":"contains","source":147,"target":926},{"edgeType":"contains","source":25,"target":1008},{"edgeType":"calls","source":951,"target":675},{"edgeType":"calls","source":2059,"target":681},{"edgeType":"contains","source":114,"target":2742},{"edgeType":"contains","source":1889,"target":1893},{"edgeType":"contains","source":1116,"target":2862},{"edgeType":"contains","source":1176,"target":2059},{"edgeType":"contains","source":121,"target":2260},{"edgeType":"calls","source":1809,"target":1824},{"edgeType":"contains","source":1178,"target":1204},{"edgeType":"contains","source":8,"target":214},{"edgeType":"calls","source":1417,"target":499},{"edgeType":"contains","source":1794,"target":1931},{"edgeType":"contains","source":1316,"target":2211},{"edgeType":"contains","source":147,"target":929},{"edgeType":"contains","source":282,"target":708},{"edgeType":"calls","source":1360,"target":948},{"edgeType":"calls","source":1312,"target":322},{"edgeType":"contains","source":202,"target":1074},{"edgeType":"calls","source":951,"target":678},{"edgeType":"calls","source":2764,"target":1023},{"edgeType":"contains","source":1428,"target":325},{"edgeType":"calls","source":1769,"target":425},{"edgeType":"calls","source":1122,"target":662},{"edgeType":"contains","source":121,"target":2263},{"edgeType":"contains","source":1116,"target":2865},{"edgeType":"calls","source":2442,"target":1228},{"edgeType":"contains","source":1414,"target":1552},{"edgeType":"contains","source":1222,"target":2219},{"edgeType":"calls","source":1417,"target":502},{"edgeType":"contains","source":1178,"target":1207},{"edgeType":"calls","source":2089,"target":1601},{"edgeType":"contains","source":1316,"target":2212},{"edgeType":"calls","source":1312,"target":321},{"edgeType":"calls","source":977,"target":664},{"edgeType":"contains","source":147,"target":928},{"edgeType":"calls","source":1596,"target":502},{"edgeType":"contains","source":121,"target":2262},{"edgeType":"contains","source":1116,"target":2864},{"edgeType":"imports","source":1234,"target":2187},{"edgeType":"contains","source":1414,"target":1553},{"edgeType":"contains","source":293,"target":1951},{"edgeType":"calls","source":2089,"target":1602},{"edgeType":"contains","source":1178,"target":1206},{"edgeType":"contains","source":1178,"target":1210},{"edgeType":"contains","source":282,"target":710},{"edgeType":"calls","source":2059,"target":678},{"edgeType":"contains","source":2334,"target":2371},{"edgeType":"calls","source":2895,"target":1981},{"edgeType":"contains","source":1259,"target":1342},{"edgeType":"imports","source":114,"target":1758},{"edgeType":"calls","source":2764,"target":1021},{"edgeType":"imports","source":1113,"target":1972},{"edgeType":"contains","source":221,"target":223},{"edgeType":"calls","source":2646,"target":451},{"edgeType":"calls","source":2442,"target":1226},{"edgeType":"contains","source":1116,"target":2867},{"edgeType":"contains","source":1316,"target":2218},{"edgeType":"calls","source":2472,"target":1089},{"edgeType":"calls","source":1907,"target":1954},{"edgeType":"contains","source":1111,"target":1172},{"edgeType":"contains","source":1435,"target":1436},{"edgeType":"calls","source":2068,"target":1191},{"edgeType":"contains","source":1178,"target":1209},{"edgeType":"contains","source":147,"target":931},{"edgeType":"contains","source":147,"target":930},{"edgeType":"calls","source":2196,"target":2246},{"edgeType":"contains","source":1411,"target":1916},{"edgeType":"contains","source":1414,"target":1559},{"edgeType":"imports","source":1113,"target":123},{"edgeType":"calls","source":2442,"target":1227},{"edgeType":"calls","source":2685,"target":2679},{"edgeType":"calls","source":479,"target":505},{"edgeType":"contains","source":1116,"target":2866},{"edgeType":"calls","source":1789,"target":326},{"edgeType":"contains","source":2428,"target":1043},{"edgeType":"contains","source":1178,"target":1208},{"edgeType":"contains","source":1176,"target":2327},{"edgeType":"contains","source":282,"target":712},{"edgeType":"contains","source":1116,"target":2077},{"edgeType":"calls","source":2096,"target":326},{"edgeType":"contains","source":1111,"target":1175},{"edgeType":"contains","source":1178,"target":1212},{"edgeType":"calls","source":1312,"target":318},{"edgeType":"calls","source":2895,"target":1979},{"edgeType":"calls","source":1596,"target":499},{"edgeType":"contains","source":135,"target":1834},{"edgeType":"contains","source":1472,"target":1872},{"edgeType":"contains","source":1794,"target":2460},{"edgeType":"contains","source":2079,"target":2082},{"edgeType":"calls","source":479,"target":508},{"edgeType":"calls","source":2792,"target":2794},{"edgeType":"contains","source":1116,"target":2869},{"edgeType":"calls","source":882,"target":435},{"edgeType":"contains","source":1316,"target":2216},{"edgeType":"calls","source":2472,"target":1087},{"edgeType":"calls","source":1968,"target":2179},{"edgeType":"imports","source":1234,"target":861},{"edgeType":"contains","source":147,"target":933},{"edgeType":"contains","source":1111,"target":1174},{"edgeType":"calls","source":1377,"target":1473},{"edgeType":"contains","source":1178,"target":1211},{"edgeType":"contains","source":282,"target":711},{"edgeType":"calls","source":2895,"target":1980},{"edgeType":"contains","source":1113,"target":2433},{"edgeType":"calls","source":2764,"target":1020},{"edgeType":"calls","source":1074,"target":296},{"edgeType":"calls","source":1432,"target":296},{"edgeType":"contains","source":972,"target":990},{"edgeType":"imports","source":1113,"target":121},{"edgeType":"calls","source":2442,"target":1225},{"edgeType":"calls","source":2076,"target":680},{"edgeType":"contains","source":1104,"target":1126},{"edgeType":"calls","source":2472,"target":1088},{"edgeType":"contains","source":1116,"target":2868},{"edgeType":"calls","source":2792,"target":2795},{"edgeType":"contains","source":147,"target":932},{"edgeType":"contains","source":1080,"target":1081},{"edgeType":"calls","source":2472,"target":1084},{"edgeType":"contains","source":1178,"target":1214},{"edgeType":"calls","source":1785,"target":976},{"edgeType":"calls","source":2895,"target":1977},{"edgeType":"contains","source":1794,"target":1938},{"edgeType":"calls","source":2083,"target":194},{"edgeType":"contains","source":1080,"target":1345},{"edgeType":"calls","source":2775,"target":2790},{"edgeType":"imports","source":1794,"target":1222},{"edgeType":"calls","source":1964,"target":976},{"edgeType":"calls","source":1846,"target":670},{"edgeType":"contains","source":972,"target":993},{"edgeType":"calls","source":2318,"target":2159},{"edgeType":"imports","source":975,"target":977},{"edgeType":"contains","source":201,"target":318},{"edgeType":"contains","source":1116,"target":2871},{"edgeType":"calls","source":2460,"target":664},{"edgeType":"contains","source":282,"target":714},{"edgeType":"contains","source":1836,"target":1429},{"edgeType":"contains","source":282,"target":713},{"edgeType":"contains","source":119,"target":2595},{"edgeType":"contains","source":1178,"target":1213},{"edgeType":"calls","source":2472,"target":1085},{"edgeType":"contains","source":89,"target":90},{"edgeType":"calls","source":1930,"target":1236},{"edgeType":"calls","source":2472,"target":1086},{"edgeType":"contains","source":1116,"target":2870},{"edgeType":"contains","source":147,"target":934},{"edgeType":"contains","source":119,"target":2598},{"edgeType":"calls","source":2895,"target":1975},{"edgeType":"contains","source":1794,"target":2200},{"edgeType":"contains","source":2155,"target":1051},{"edgeType":"calls","source":1063,"target":1162},{"edgeType":"contains","source":1111,"target":1179},{"edgeType":"calls","source":2472,"target":1082},{"edgeType":"contains","source":1178,"target":1216},{"edgeType":"contains","source":1052,"target":1158},{"edgeType":"imports","source":457,"target":121},{"edgeType":"calls","source":2842,"target":976},{"edgeType":"calls","source":2316,"target":2219},{"edgeType":"calls","source":1768,"target":976},{"edgeType":"contains","source":1625,"target":1626},{"edgeType":"contains","source":201,"target":320},{"edgeType":"contains","source":147,"target":937},{"edgeType":"contains","source":282,"target":716},{"edgeType":"contains","source":1116,"target":2873},{"edgeType":"calls","source":2895,"target":1976},{"edgeType":"contains","source":119,"target":2597},{"edgeType":"calls","source":2059,"target":675},{"edgeType":"calls","source":1063,"target":1161},{"edgeType":"contains","source":1178,"target":1215},{"edgeType":"calls","source":2361,"target":296},{"edgeType":"calls","source":2472,"target":1083},{"edgeType":"calls","source":2097,"target":2138},{"edgeType":"contains","source":1836,"target":1956},{"edgeType":"contains","source":1094,"target":1176},{"edgeType":"imports","source":1836,"target":446},{"edgeType":"calls","source":479,"target":503},{"edgeType":"contains","source":201,"target":319},{"edgeType":"contains","source":147,"target":936},{"edgeType":"contains","source":1116,"target":2872},{"edgeType":"contains","source":1721,"target":1822},{"edgeType":"contains","source":282,"target":715},{"edgeType":"contains","source":1116,"target":2876},{"edgeType":"calls","source":2172,"target":2188},{"edgeType":"contains","source":1052,"target":1160},{"edgeType":"calls","source":1024,"target":1043},{"edgeType":"contains","source":2137,"target":2144},{"edgeType":"contains","source":201,"target":322},{"edgeType":"imports","source":1234,"target":1930},{"edgeType":"contains","source":147,"target":939},{"edgeType":"contains","source":282,"target":718},{"edgeType":"calls","source":1534,"target":296},{"edgeType":"contains","source":119,"target":2600},{"edgeType":"calls","source":2083,"target":2041},{"edgeType":"contains","source":1116,"target":2875},{"edgeType":"calls","source":2383,"target":669},{"edgeType":"calls","source":1188,"target":451},{"edgeType":"contains","source":1111,"target":1180},{"edgeType":"imports","source":975,"target":446},{"edgeType":"calls","source":164,"target":1012},{"edgeType":"contains","source":1178,"target":1217},{"edgeType":"contains","source":1,"target":443},{"edgeType":"calls","source":1515,"target":356},{"edgeType":"contains","source":1316,"target":2227},{"edgeType":"imports","source":1447,"target":1668},{"edgeType":"calls","source":1938,"target":984},{"edgeType":"imports","source":457,"target":119},{"edgeType":"calls","source":2071,"target":1089},{"edgeType":"calls","source":2186,"target":170},{"edgeType":"contains","source":201,"target":321},{"edgeType":"contains","source":1501,"target":1513},{"edgeType":"contains","source":147,"target":938},{"edgeType":"contains","source":1650,"target":1651},{"edgeType":"contains","source":2137,"target":2145},{"edgeType":"contains","source":282,"target":717},{"edgeType":"calls","source":2664,"target":1736},{"edgeType":"contains","source":1116,"target":2874},{"edgeType":"contains","source":119,"target":2599},{"edgeType":"calls","source":2085,"target":1712},{"edgeType":"calls","source":2228,"target":2300},{"edgeType":"calls","source":1930,"target":1235},{"edgeType":"contains","source":201,"target":324},{"edgeType":"calls","source":2891,"target":2888},{"edgeType":"contains","source":147,"target":941},{"edgeType":"imports","source":1234,"target":1398},{"edgeType":"contains","source":282,"target":720},{"edgeType":"imports","source":1447,"target":346},{"edgeType":"calls","source":951,"target":666},{"edgeType":"contains","source":427,"target":2303},{"edgeType":"contains","source":119,"target":2337},{"edgeType":"contains","source":1111,"target":1182},{"edgeType":"contains","source":1,"target":181},{"edgeType":"contains","source":1836,"target":1960},{"edgeType":"calls","source":1812,"target":664},{"edgeType":"contains","source":6,"target":1347},{"edgeType":"contains","source":1031,"target":1812},{"edgeType":"contains","source":76,"target":1292},{"edgeType":"contains","source":1316,"target":2225},{"edgeType":"contains","source":147,"target":940},{"edgeType":"contains","source":2162,"target":311},{"edgeType":"contains","source":282,"target":719},{"edgeType":"contains","source":1411,"target":1923},{"edgeType":"calls","source":1986,"target":1876},{"edgeType":"calls","source":2672,"target":2044},{"edgeType":"contains","source":1116,"target":2847},{"edgeType":"contains","source":1543,"target":1766},{"edgeType":"contains","source":975,"target":1404},{"edgeType":"calls","source":1360,"target":170},{"edgeType":"calls","source":1000,"target":1024},{"edgeType":"imports","source":1234,"target":851},{"edgeType":"contains","source":1080,"target":1320},{"edgeType":"calls","source":1598,"target":1512},{"edgeType":"contains","source":147,"target":910},{"edgeType":"calls","source":1952,"target":2165},{"edgeType":"imports","source":980,"target":1063},{"edgeType":"calls","source":2672,"target":2045},{"edgeType":"calls","source":2063,"target":1895},{"edgeType":"contains","source":1116,"target":2846},{"edgeType":"contains","source":858,"target":1595},{"edgeType":"contains","source":255,"target":997},{"edgeType":"contains","source":1447,"target":1308},{"edgeType":"calls","source":2154,"target":662},{"edgeType":"contains","source":310,"target":349},{"edgeType":"calls","source":213,"target":315},{"edgeType":"contains","source":2441,"target":2469},{"edgeType":"calls","source":2420,"target":2194},{"edgeType":"calls","source":1748,"target":1089},{"edgeType":"contains","source":297,"target":487},{"edgeType":"imports","source":1447,"target":1119},{"edgeType":"contains","source":147,"target":909},{"edgeType":"calls","source":2171,"target":664},{"edgeType":"calls","source":2085,"target":948},{"edgeType":"contains","source":121,"target":2247},{"edgeType":"contains","source":1116,"target":2849},{"edgeType":"contains","source":1543,"target":1764},{"edgeType":"contains","source":1836,"target":1930},{"edgeType":"calls","source":2614,"target":669},{"edgeType":"calls","source":1517,"target":326},{"edgeType":"calls","source":2169,"target":194},{"edgeType":"calls","source":1326,"target":1226},{"edgeType":"contains","source":147,"target":912},{"edgeType":"contains","source":1078,"target":2441},{"edgeType":"calls","source":2662,"target":1824},{"edgeType":"calls","source":1724,"target":515},{"edgeType":"calls","source":2186,"target":196},{"edgeType":"calls","source":997,"target":326},{"edgeType":"contains","source":117,"target":257},{"edgeType":"contains","source":260,"target":1109},{"edgeType":"calls","source":2672,"target":2043},{"edgeType":"contains","source":1116,"target":2848},{"edgeType":"calls","source":674,"target":296},{"edgeType":"calls","source":2541,"target":290},{"edgeType":"contains","source":192,"target":838},{"edgeType":"calls","source":1326,"target":1225},{"edgeType":"contains","source":147,"target":911},{"edgeType":"contains","source":293,"target":1406},{"edgeType":"calls","source":1724,"target":514},{"edgeType":"contains","source":1969,"target":2301},{"edgeType":"contains","source":119,"target":2572},{"edgeType":"contains","source":114,"target":2727},{"edgeType":"calls","source":164,"target":251},{"edgeType":"imports","source":1447,"target":851},{"edgeType":"calls","source":2338,"target":502},{"edgeType":"contains","source":1116,"target":2851},{"edgeType":"calls","source":2246,"target":976},{"edgeType":"contains","source":1316,"target":2201},{"edgeType":"calls","source":2000,"target":1202},{"edgeType":"contains","source":204,"target":205},{"edgeType":"calls","source":1686,"target":1687},{"edgeType":"contains","source":147,"target":915},{"edgeType":"calls","source":660,"target":1253},{"edgeType":"contains","source":1178,"target":1193},{"edgeType":"contains","source":147,"target":914},{"edgeType":"contains","source":8,"target":203},{"edgeType":"calls","source":1748,"target":1086},{"edgeType":"contains","source":293,"target":1409},{"edgeType":"calls","source":1360,"target":958},{"edgeType":"contains","source":2252,"target":2254},{"edgeType":"calls","source":213,"target":312},{"edgeType":"contains","source":1116,"target":2322},{"edgeType":"contains","source":119,"target":2575},{"edgeType":"calls","source":1244,"target":326},{"edgeType":"calls","source":1943,"target":326},{"edgeType":"calls","source":2186,"target":194},{"edgeType":"calls","source":2677,"target":2678},{"edgeType":"contains","source":1104,"target":1108},{"edgeType":"calls","source":270,"target":129},{"edgeType":"contains","source":1116,"target":2850},{"edgeType":"contains","source":192,"target":840},{"edgeType":"contains","source":121,"target":1984},{"edgeType":"calls","source":2000,"target":1201},{"edgeType":"contains","source":2764,"target":2767},{"edgeType":"calls","source":2019,"target":1669},{"edgeType":"contains","source":147,"target":913},{"edgeType":"calls","source":1835,"target":502},{"edgeType":"calls","source":1380,"target":1394},{"edgeType":"calls","source":1748,"target":1085},{"edgeType":"contains","source":119,"target":2574},{"edgeType":"calls","source":2186,"target":195},{"edgeType":"contains","source":87,"target":131},{"edgeType":"contains","source":117,"target":258},{"edgeType":"contains","source":119,"target":1253},{"edgeType":"calls","source":449,"target":661},{"edgeType":"calls","source":993,"target":974},{"edgeType":"calls","source":2689,"target":982},{"edgeType":"contains","source":1116,"target":2853},{"edgeType":"calls","source":2442,"target":976},{"edgeType":"contains","source":1472,"target":1591},{"edgeType":"contains","source":204,"target":207},{"edgeType":"contains","source":147,"target":917},{"edgeType":"contains","source":2441,"target":2470},{"edgeType":"imports","source":307,"target":513},{"edgeType":"contains","source":1178,"target":1195},{"edgeType":"calls","source":1748,"target":1088},{"edgeType":"contains","source":1969,"target":2304},{"edgeType":"contains","source":121,"target":2251},{"edgeType":"contains","source":457,"target":2141},{"edgeType":"calls","source":2677,"target":2676},{"edgeType":"contains","source":972,"target":974},{"edgeType":"contains","source":192,"target":842},{"edgeType":"calls","source":1994,"target":2182},{"edgeType":"contains","source":1116,"target":2852},{"edgeType":"contains","source":204,"target":206},{"edgeType":"contains","source":202,"target":268},{"edgeType":"contains","source":147,"target":916},{"edgeType":"imports","source":1392,"target":175},{"edgeType":"calls","source":2203,"target":194},{"edgeType":"calls","source":1748,"target":1087},{"edgeType":"contains","source":1178,"target":1194},{"edgeType":"contains","source":293,"target":1410},{"edgeType":"contains","source":1176,"target":2313},{"edgeType":"calls","source":951,"target":690},{"edgeType":"calls","source":2689,"target":984},{"edgeType":"calls","source":1240,"target":451},{"edgeType":"calls","source":1726,"target":976},{"edgeType":"contains","source":1969,"target":1248},{"edgeType":"contains","source":1794,"target":2445},{"edgeType":"calls","source":1470,"target":451},{"edgeType":"contains","source":1316,"target":2205},{"edgeType":"contains","source":1794,"target":2450},{"edgeType":"calls","source":2010,"target":1945},{"edgeType":"calls","source":1001,"target":984},{"edgeType":"contains","source":147,"target":919},{"edgeType":"calls","source":1122,"target":669},{"edgeType":"contains","source":1116,"target":2855},{"edgeType":"calls","source":1591,"target":664},{"edgeType":"calls","source":2059,"target":690},{"edgeType":"contains","source":2153,"target":2156},{"edgeType":"contains","source":1178,"target":1197},{"edgeType":"contains","source":114,"target":2734},{"edgeType":"calls","source":1748,"target":1082},{"edgeType":"contains","source":1428,"target":319},{"edgeType":"calls","source":1835,"target":499},{"edgeType":"contains","source":1897,"target":1900},{"edgeType":"contains","source":457,"target":2143},{"edgeType":"calls","source":2809,"target":2810},{"edgeType":"calls","source":2341,"target":670},{"edgeType":"contains","source":87,"target":135},{"edgeType":"calls","source":2615,"target":1954},{"edgeType":"contains","source":1316,"target":2206},{"edgeType":"calls","source":2338,"target":499},{"edgeType":"calls","source":2010,"target":1944},{"edgeType":"calls","source":2196,"target":673},{"edgeType":"contains","source":122,"target":1428},{"edgeType":"contains","source":1116,"target":2854},{"edgeType":"contains","source":147,"target":918},{"edgeType":"imports","source":1113,"target":119},{"edgeType":"contains","source":1428,"target":320},{"edgeType":"contains","source":87,"target":1721},{"edgeType":"contains","source":1178,"target":1196},{"edgeType":"contains","source":119,"target":2578},{"edgeType":"contains","source":114,"target":2733},{"edgeType":"contains","source":1031,"target":1789},{"edgeType":"calls","source":1633,"target":682},{"edgeType":"contains","source":1414,"target":1547},{"edgeType":"calls","source":2023,"target":2069},{"edgeType":"contains","source":114,"target":91},{"edgeType":"calls","source":1312,"target":327},{"edgeType":"imports","source":1234,"target":860},{"edgeType":"contains","source":352,"target":2226},{"edgeType":"contains","source":457,"target":2142},{"edgeType":"calls","source":2764,"target":1560},{"edgeType":"calls","source":2186,"target":187},{"edgeType":"contains","source":147,"target":921},{"edgeType":"calls","source":1633,"target":1478},{"edgeType":"calls","source":2000,"target":1200},{"edgeType":"contains","source":1116,"target":2857},{"edgeType":"calls","source":2442,"target":1236},{"edgeType":"contains","source":135,"target":2085},{"edgeType":"contains","source":114,"target":2736},{"edgeType":"contains","source":6,"target":7},{"edgeType":"contains","source":1031,"target":1528},{"edgeType":"calls","source":2297,"target":2296},{"edgeType":"contains","source":1178,"target":1199},{"edgeType":"calls","source":1748,"target":1084},{"edgeType":"calls","source":1380,"target":1393},{"edgeType":"calls","source":2764,"target":1561},{"edgeType":"contains","source":127,"target":1011},{"edgeType":"imports","source":1836,"target":429},{"edgeType":"calls","source":2246,"target":2292},{"edgeType":"calls","source":1939,"target":976},{"edgeType":"calls","source":1344,"target":1187},{"edgeType":"contains","source":147,"target":920},{"edgeType":"contains","source":1116,"target":2856},{"edgeType":"contains","source":2877,"target":2437},{"edgeType":"contains","source":114,"target":2735},{"edgeType":"calls","source":2614,"target":662},{"edgeType":"contains","source":2153,"target":2155},{"edgeType":"calls","source":1748,"target":1083},{"edgeType":"contains","source":1178,"target":1198},{"edgeType":"contains","source":1428,"target":318},{"edgeType":"calls","source":1824,"target":1898},{"edgeType":"contains","source":1113,"target":2420},{"edgeType":"contains","source":1641,"target":1643},{"edgeType":"calls","source":1117,"target":296},{"edgeType":"calls","source":1278,"target":326},{"edgeType":"calls","source":1248,"target":194},{"edgeType":"calls","source":2319,"target":290},{"edgeType":"calls","source":1312,"target":324},{"edgeType":"calls","source":1011,"target":670},{"edgeType":"contains","source":147,"target":923},{"edgeType":"contains","source":293,"target":1418},{"edgeType":"calls","source":1352,"target":670},{"edgeType":"calls","source":2685,"target":2157},{"edgeType":"contains","source":114,"target":2739},{"edgeType":"contains","source":1116,"target":2859},{"edgeType":"calls","source":128,"target":296},{"edgeType":"contains","source":126,"target":1310},{"edgeType":"calls","source":1308,"target":976},{"edgeType":"contains","source":1985,"target":2083},{"edgeType":"contains","source":1178,"target":1201},{"edgeType":"imports","source":303,"target":119},{"edgeType":"imports","source":1447,"target":860},{"edgeType":"calls","source":2842,"target":2840},{"edgeType":"imports","source":293,"target":1222},{"edgeType":"imports","source":352,"target":450},{"edgeType":"contains","source":1113,"target":2423},{"edgeType":"contains","source":1116,"target":1537},{"edgeType":"calls","source":2186,"target":186},{"edgeType":"contains","source":147,"target":922},{"edgeType":"imports","source":1969,"target":1853},{"edgeType":"calls","source":1238,"target":1296},{"edgeType":"contains","source":2375,"target":2414},{"edgeType":"calls","source":2442,"target":1235},{"edgeType":"contains","source":1428,"target":324},{"edgeType":"calls","source":1339,"target":1336},{"edgeType":"contains","source":1116,"target":2858},{"edgeType":"contains","source":114,"target":2738},{"edgeType":"contains","source":1794,"target":1927},{"edgeType":"calls","source":2293,"target":569},{"edgeType":"calls","source":1352,"target":1725},{"edgeType":"contains","source":1178,"target":1200},{"edgeType":"contains","source":121,"target":2256},{"edgeType":"contains","source":1116,"target":2329},{"edgeType":"contains","source":113,"target":129},{"edgeType":"calls","source":2429,"target":1899},{"edgeType":"imports","source":131,"target":164},{"edgeType":"imports","source":5,"target":106},{"edgeType":"contains","source":1316,"target":2207},{"edgeType":"contains","source":147,"target":925},{"edgeType":"calls","source":1001,"target":982},{"edgeType":"calls","source":2813,"target":2415},{"edgeType":"calls","source":1769,"target":429},{"edgeType":"contains","source":1428,"target":321},{"edgeType":"contains","source":1116,"target":2861},{"edgeType":"contains","source":126,"target":255},{"edgeType":"calls","source":1782,"target":290},{"edgeType":"contains","source":1111,"target":1166},{"edgeType":"contains","source":1178,"target":1203},{"edgeType":"contains","source":1111,"target":1430},{"edgeType":"contains","source":11,"target":1177},{"edgeType":"calls","source":2685,"target":2684},{"edgeType":"calls","source":2677,"target":290},{"edgeType":"calls","source":1930,"target":194},{"edgeType":"contains","source":1116,"target":2332},{"edgeType":"contains","source":1316,"target":2208},{"edgeType":"calls","source":1312,"target":325},{"edgeType":"imports","source":5,"target":107},{"edgeType":"contains","source":147,"target":924},{"edgeType":"calls","source":2186,"target":184},{"edgeType":"calls","source":1907,"target":2228},{"edgeType":"contains","source":60,"target":185},{"edgeType":"calls","source":951,"target":681},{"edgeType":"contains","source":119,"target":2585},{"edgeType":"contains","source":114,"target":2740},{"edgeType":"contains","source":305,"target":782},{"edgeType":"contains","source":1116,"target":2860},{"edgeType":"contains","source":457,"target":2148},{"edgeType":"contains","source":1501,"target":2023},{"edgeType":"contains","source":265,"target":965},{"edgeType":"contains","source":1428,"target":322},{"edgeType":"calls","source":2842,"target":2839},{"edgeType":"contains","source":1794,"target":1925},{"edgeType":"calls","source":1461,"target":1255},{"edgeType":"calls","source":1470,"target":976},{"edgeType":"contains","source":1178,"target":1202},{"edgeType":"imports","source":1836,"target":425},{"edgeType":"contains","source":1641,"target":1647},{"edgeType":"calls","source":2682,"target":664},{"edgeType":"calls","source":2895,"target":1688},{"edgeType":"calls","source":2555,"target":1129},{"edgeType":"calls","source":2138,"target":1900},{"edgeType":"calls","source":1315,"target":194},{"edgeType":"calls","source":2228,"target":2281},{"edgeType":"calls","source":1240,"target":669},{"edgeType":"contains","source":147,"target":894},{"edgeType":"contains","source":261,"target":267},{"edgeType":"calls","source":1558,"target":589},{"edgeType":"contains","source":1794,"target":2689},{"edgeType":"contains","source":1745,"target":2094},{"edgeType":"contains","source":219,"target":512},{"edgeType":"calls","source":1984,"target":1124},{"edgeType":"calls","source":1189,"target":664},{"edgeType":"contains","source":137,"target":940},{"edgeType":"imports","source":1234,"target":1429},{"edgeType":"calls","source":2626,"target":2628},{"edgeType":"calls","source":1793,"target":1231},{"edgeType":"calls","source":2228,"target":2282},{"edgeType":"calls","source":2437,"target":1088},{"edgeType":"calls","source":1253,"target":1322},{"edgeType":"contains","source":298,"target":440},{"edgeType":"contains","source":219,"target":511},{"edgeType":"calls","source":1081,"target":1105},{"edgeType":"contains","source":1794,"target":2426},{"edgeType":"calls","source":1733,"target":976},{"edgeType":"contains","source":137,"target":939},{"edgeType":"calls","source":2448,"target":1012},{"edgeType":"contains","source":1794,"target":2691},{"edgeType":"contains","source":1969,"target":1758},{"edgeType":"calls","source":1426,"target":187},{"edgeType":"contains","source":307,"target":1482},{"edgeType":"calls","source":2228,"target":2283},{"edgeType":"calls","source":2437,"target":1089},{"edgeType":"calls","source":2253,"target":451},{"edgeType":"contains","source":1310,"target":1311},{"edgeType":"calls","source":2228,"target":2279},{"edgeType":"contains","source":352,"target":1676},{"edgeType":"calls","source":2458,"target":1227},{"edgeType":"contains","source":147,"target":896},{"edgeType":"calls","source":1812,"target":1966},{"edgeType":"contains","source":1745,"target":2092},{"edgeType":"contains","source":1615,"target":1630},{"edgeType":"contains","source":137,"target":942},{"edgeType":"calls","source":1932,"target":1945},{"edgeType":"contains","source":1482,"target":1525},{"edgeType":"calls","source":1912,"target":451},{"edgeType":"calls","source":2437,"target":1086},{"edgeType":"contains","source":119,"target":2028},{"edgeType":"contains","source":76,"target":983},{"edgeType":"calls","source":1812,"target":1965},{"edgeType":"contains","source":147,"target":895},{"edgeType":"calls","source":2228,"target":2280},{"edgeType":"contains","source":303,"target":1080},{"edgeType":"calls","source":1247,"target":1246},{"edgeType":"contains","source":996,"target":1002},{"edgeType":"calls","source":2585,"target":462},{"edgeType":"contains","source":2375,"target":2383},{"edgeType":"calls","source":2458,"target":1228},{"edgeType":"contains","source":1794,"target":2688},{"edgeType":"calls","source":285,"target":678},{"edgeType":"contains","source":202,"target":1040},{"edgeType":"contains","source":1745,"target":2093},{"edgeType":"calls","source":660,"target":680},{"edgeType":"contains","source":152,"target":211},{"edgeType":"contains","source":127,"target":986},{"edgeType":"contains","source":980,"target":1762},{"edgeType":"calls","source":1984,"target":1125},{"edgeType":"contains","source":1411,"target":1877},{"edgeType":"contains","source":2429,"target":2559},{"edgeType":"contains","source":63,"target":64},{"edgeType":"calls","source":1557,"target":356},{"edgeType":"contains","source":200,"target":837},{"edgeType":"contains","source":137,"target":941},{"edgeType":"calls","source":1932,"target":1944},{"edgeType":"contains","source":1111,"target":1136},{"edgeType":"calls","source":2219,"target":710},{"edgeType":"calls","source":2171,"target":2198},{"edgeType":"imports","source":1234,"target":1956},{"edgeType":"calls","source":2437,"target":1087},{"edgeType":"contains","source":147,"target":898},{"edgeType":"contains","source":1013,"target":1271},{"edgeType":"imports","source":1447,"target":1429},{"edgeType":"calls","source":1402,"target":664},{"edgeType":"contains","source":352,"target":1678},{"edgeType":"calls","source":2458,"target":1225},{"edgeType":"contains","source":261,"target":271},{"edgeType":"calls","source":2228,"target":2277},{"edgeType":"contains","source":996,"target":1005},{"edgeType":"contains","source":200,"target":841},{"edgeType":"contains","source":121,"target":2232},{"edgeType":"contains","source":1745,"target":2099},{"edgeType":"calls","source":2651,"target":2642},{"edgeType":"calls","source":1767,"target":976},{"edgeType":"calls","source":1426,"target":184},{"edgeType":"calls","source":2437,"target":1084},{"edgeType":"calls","source":2096,"target":290},{"edgeType":"calls","source":1470,"target":669},{"edgeType":"calls","source":2458,"target":1226},{"edgeType":"contains","source":147,"target":897},{"edgeType":"calls","source":2228,"target":2278},{"edgeType":"contains","source":352,"target":1677},{"edgeType":"calls","source":974,"target":982},{"edgeType":"calls","source":1946,"target":976},{"edgeType":"calls","source":2585,"target":460},{"edgeType":"calls","source":1715,"target":2059},{"edgeType":"calls","source":2256,"target":2203},{"edgeType":"contains","source":87,"target":114},{"edgeType":"calls","source":2028,"target":1869},{"edgeType":"calls","source":2389,"target":194},{"edgeType":"calls","source":270,"target":344},{"edgeType":"contains","source":200,"target":839},{"edgeType":"contains","source":162,"target":168},{"edgeType":"calls","source":2437,"target":1085},{"edgeType":"contains","source":25,"target":1508},{"edgeType":"calls","source":2882,"target":2881},{"edgeType":"contains","source":3,"target":76},{"edgeType":"calls","source":2219,"target":708},{"edgeType":"calls","source":1771,"target":326},{"edgeType":"contains","source":1113,"target":2137},{"edgeType":"calls","source":1251,"target":326},{"edgeType":"calls","source":2683,"target":326},{"edgeType":"calls","source":2118,"target":664},{"edgeType":"calls","source":2228,"target":2275},{"edgeType":"contains","source":11,"target":95},{"edgeType":"calls","source":1528,"target":988},{"edgeType":"calls","source":285,"target":675},{"edgeType":"contains","source":2334,"target":2336},{"edgeType":"calls","source":1511,"target":194},{"edgeType":"contains","source":310,"target":339},{"edgeType":"calls","source":1430,"target":326},{"edgeType":"contains","source":154,"target":155},{"edgeType":"imports","source":135,"target":346},{"edgeType":"calls","source":2228,"target":690},{"edgeType":"calls","source":1426,"target":186},{"edgeType":"calls","source":2085,"target":1952},{"edgeType":"contains","source":147,"target":900},{"edgeType":"contains","source":1745,"target":1833},{"edgeType":"contains","source":1176,"target":1240},{"edgeType":"contains","source":11,"target":94},{"edgeType":"calls","source":1380,"target":290},{"edgeType":"calls","source":974,"target":984},{"edgeType":"calls","source":2437,"target":1082},{"edgeType":"calls","source":2228,"target":2276},{"edgeType":"contains","source":1078,"target":2428},{"edgeType":"calls","source":2651,"target":2640},{"edgeType":"contains","source":255,"target":1251},{"edgeType":"contains","source":443,"target":444},{"edgeType":"calls","source":2611,"target":1502},{"edgeType":"contains","source":2493,"target":2428},{"edgeType":"calls","source":1631,"target":436},{"edgeType":"calls","source":2437,"target":1083},{"edgeType":"contains","source":25,"target":1510},{"edgeType":"contains","source":6,"target":1042},{"edgeType":"contains","source":147,"target":899},{"edgeType":"calls","source":2764,"target":984},{"edgeType":"calls","source":1319,"target":326},{"edgeType":"contains","source":1013,"target":1275},{"edgeType":"contains","source":1052,"target":1123},{"edgeType":"contains","source":1482,"target":1535},{"edgeType":"contains","source":1472,"target":1845},{"edgeType":"contains","source":87,"target":1969},{"edgeType":"calls","source":2228,"target":2273},{"edgeType":"contains","source":126,"target":760},{"edgeType":"calls","source":2611,"target":1499},{"edgeType":"calls","source":1426,"target":973},{"edgeType":"contains","source":996,"target":1009},{"edgeType":"calls","source":1968,"target":1876},{"edgeType":"calls","source":2018,"target":326},{"edgeType":"contains","source":1880,"target":1882},{"edgeType":"contains","source":980,"target":1769},{"edgeType":"contains","source":1116,"target":2838},{"edgeType":"contains","source":147,"target":902},{"edgeType":"imports","source":1447,"target":121},{"edgeType":"contains","source":1794,"target":2698},{"edgeType":"contains","source":1335,"target":1336},{"edgeType":"calls","source":2138,"target":2157},{"edgeType":"calls","source":2672,"target":666},{"edgeType":"calls","source":2228,"target":2274},{"edgeType":"calls","source":2360,"target":296},{"edgeType":"contains","source":44,"target":130},{"edgeType":"imports","source":307,"target":843},{"edgeType":"calls","source":1824,"target":1054},{"edgeType":"imports","source":1543,"target":843},{"edgeType":"contains","source":121,"target":122},{"edgeType":"contains","source":154,"target":156},{"edgeType":"imports","source":57,"target":137},{"edgeType":"contains","source":310,"target":340},{"edgeType":"calls","source":2474,"target":462},{"edgeType":"contains","source":1880,"target":1883},{"edgeType":"calls","source":1535,"target":499},{"edgeType":"contains","source":1116,"target":2837},{"edgeType":"calls","source":1800,"target":476},{"edgeType":"calls","source":2618,"target":2076},{"edgeType":"calls","source":1269,"target":1346},{"edgeType":"contains","source":1335,"target":1337},{"edgeType":"contains","source":147,"target":901},{"edgeType":"calls","source":1596,"target":458},{"edgeType":"calls","source":2764,"target":982},{"edgeType":"calls","source":1598,"target":664},{"edgeType":"contains","source":1501,"target":2265},{"edgeType":"calls","source":2611,"target":1497},{"edgeType":"contains","source":297,"target":482},{"edgeType":"contains","source":1335,"target":1598},{"edgeType":"contains","source":1116,"target":2840},{"edgeType":"contains","source":2441,"target":2458},{"edgeType":"imports","source":1447,"target":1176},{"edgeType":"contains","source":1013,"target":1276},{"edgeType":"calls","source":1240,"target":662},{"edgeType":"contains","source":11,"target":98},{"edgeType":"calls","source":2022,"target":2053},{"edgeType":"calls","source":1535,"target":502},{"edgeType":"calls","source":2611,"target":1498},{"edgeType":"calls","source":2019,"target":296},{"edgeType":"contains","source":55,"target":56},{"edgeType":"calls","source":1345,"target":1106},{"edgeType":"contains","source":127,"target":995},{"edgeType":"calls","source":1081,"target":1098},{"edgeType":"calls","source":1095,"target":664},{"edgeType":"calls","source":2474,"target":460},{"edgeType":"contains","source":1880,"target":1881},{"edgeType":"calls","source":2083,"target":690},{"edgeType":"contains","source":147,"target":903},{"edgeType":"contains","source":81,"target":1628},{"edgeType":"contains","source":1116,"target":2839},{"edgeType":"calls","source":2764,"target":1776},{"edgeType":"contains","source":1013,"target":1015},{"edgeType":"imports","source":305,"target":107},{"edgeType":"contains","source":121,"target":2241},{"edgeType":"calls","source":2751,"target":326},{"edgeType":"contains","source":1013,"target":1279},{"edgeType":"calls","source":2640,"target":1124},{"edgeType":"calls","source":1470,"target":662},{"edgeType":"contains","source":352,"target":2215},{"edgeType":"contains","source":1119,"target":1164},{"edgeType":"calls","source":1550,"target":296},{"edgeType":"contains","source":2483,"target":2484},{"edgeType":"calls","source":1812,"target":1687},{"edgeType":"calls","source":1845,"target":664},{"edgeType":"contains","source":1880,"target":1886},{"edgeType":"calls","source":2022,"target":462},{"edgeType":"imports","source":1234,"target":1963},{"edgeType":"contains","source":297,"target":484},{"edgeType":"calls","source":2611,"target":1495},{"edgeType":"contains","source":147,"target":906},{"edgeType":"calls","source":1834,"target":476},{"edgeType":"contains","source":1794,"target":2702},{"edgeType":"contains","source":1335,"target":1340},{"edgeType":"imports","source":307,"target":309},{"edgeType":"contains","source":1116,"target":2842},{"edgeType":"calls","source":1715,"target":2051},{"edgeType":"calls","source":2173,"target":1332},{"edgeType":"contains","source":119,"target":2566},{"edgeType":"contains","source":1013,"target":1014},{"edgeType":"contains","source":430,"target":1117},{"edgeType":"calls","source":2640,"target":1125},{"edgeType":"contains","source":1119,"target":1163},{"edgeType":"contains","source":310,"target":345},{"edgeType":"calls","source":1888,"target":387},{"edgeType":"contains","source":1880,"target":1887},{"edgeType":"contains","source":2441,"target":2465},{"edgeType":"contains","source":297,"target":483},{"edgeType":"calls","source":2611,"target":1496},{"edgeType":"contains","source":1513,"target":844},{"edgeType":"contains","source":147,"target":905},{"edgeType":"calls","source":2764,"target":1774},{"edgeType":"calls","source":1468,"target":194},{"edgeType":"calls","source":2173,"target":1333},{"edgeType":"calls","source":1715,"target":2050},{"edgeType":"calls","source":1877,"target":1256},{"edgeType":"calls","source":2173,"target":1329},{"edgeType":"contains","source":87,"target":1447},{"edgeType":"calls","source":1715,"target":1261},{"edgeType":"contains","source":1116,"target":2845},{"edgeType":"calls","source":2228,"target":681},{"edgeType":"calls","source":1426,"target":971},{"edgeType":"contains","source":310,"target":348},{"edgeType":"contains","source":1794,"target":2171},{"edgeType":"calls","source":1907,"target":1915},{"edgeType":"contains","source":297,"target":486},{"edgeType":"contains","source":1880,"target":1884},{"edgeType":"contains","source":147,"target":908},{"edgeType":"calls","source":2353,"target":2356},{"edgeType":"contains","source":126,"target":1031},{"edgeType":"contains","source":1836,"target":1398},{"edgeType":"contains","source":1794,"target":2700},{"edgeType":"contains","source":1854,"target":1897},{"edgeType":"calls","source":2389,"target":976},{"edgeType":"contains","source":1013,"target":1016},{"edgeType":"contains","source":1116,"target":2844},{"edgeType":"calls","source":2173,"target":1330},{"edgeType":"calls","source":1453,"target":1454},{"edgeType":"contains","source":121,"target":2242},{"edgeType":"imports","source":1234,"target":904},{"edgeType":"contains","source":310,"target":347},{"edgeType":"contains","source":1119,"target":1165},{"edgeType":"contains","source":297,"target":485},{"edgeType":"contains","source":1880,"target":1885},{"edgeType":"contains","source":1116,"target":465},{"edgeType":"imports","source":135,"target":91},{"edgeType":"calls","source":2353,"target":2357},{"edgeType":"contains","source":147,"target":907},{"edgeType":"contains","source":117,"target":252},{"edgeType":"contains","source":153,"target":721},{"edgeType":"calls","source":1272,"target":194},{"edgeType":"imports","source":1234,"target":1960},{"edgeType":"contains","source":1335,"target":1339},{"edgeType":"calls","source":1361,"target":1399},{"edgeType":"calls","source":1532,"target":326},{"edgeType":"calls","source":285,"target":666},{"edgeType":"calls","source":1715,"target":2052},{"edgeType":"calls","source":2173,"target":1331},{"edgeType":"contains","source":1116,"target":2843},{"edgeType":"contains","source":255,"target":1229},{"edgeType":"contains","source":137,"target":923},{"edgeType":"contains","source":880,"target":881},{"edgeType":"contains","source":1543,"target":1733},{"edgeType":"contains","source":473,"target":549},{"edgeType":"contains","source":119,"target":2010},{"edgeType":"contains","source":1621,"target":1694},{"edgeType":"contains","source":443,"target":950},{"edgeType":"calls","source":2071,"target":1086},{"edgeType":"contains","source":2160,"target":2162},{"edgeType":"calls","source":1247,"target":1261},{"edgeType":"contains","source":1836,"target":1371},{"edgeType":"contains","source":117,"target":222},{"edgeType":"imports","source":1234,"target":91},{"edgeType":"calls","source":2672,"target":690},{"edgeType":"contains","source":219,"target":495},{"edgeType":"calls","source":1404,"target":1415},{"edgeType":"contains","source":980,"target":2801},{"edgeType":"contains","source":473,"target":548},{"edgeType":"contains","source":137,"target":922},{"edgeType":"calls","source":1878,"target":462},{"edgeType":"contains","source":1116,"target":2813},{"edgeType":"contains","source":298,"target":952},{"edgeType":"calls","source":1900,"target":1894},{"edgeType":"calls","source":141,"target":664},{"edgeType":"contains","source":310,"target":316},{"edgeType":"calls","source":2085,"target":1711},{"edgeType":"contains","source":44,"target":105},{"edgeType":"contains","source":2383,"target":2385},{"edgeType":"calls","source":2196,"target":2234},{"edgeType":"calls","source":1930,"target":1228},{"edgeType":"calls","source":2008,"target":1981},{"edgeType":"calls","source":2071,"target":1085},{"edgeType":"calls","source":2658,"target":1918},{"edgeType":"contains","source":443,"target":949},{"edgeType":"contains","source":2160,"target":2163},{"edgeType":"calls","source":1810,"target":984},{"edgeType":"contains","source":147,"target":876},{"edgeType":"contains","source":25,"target":959},{"edgeType":"calls","source":2552,"target":976},{"edgeType":"contains","source":513,"target":629},{"edgeType":"contains","source":980,"target":2800},{"edgeType":"contains","source":980,"target":2804},{"edgeType":"contains","source":137,"target":925},{"edgeType":"contains","source":1116,"target":2816},{"edgeType":"contains","source":473,"target":551},{"edgeType":"contains","source":1472,"target":1818},{"edgeType":"calls","source":2383,"target":662},{"edgeType":"calls","source":2076,"target":669},{"edgeType":"calls","source":1188,"target":1243},{"edgeType":"contains","source":302,"target":303},{"edgeType":"contains","source":981,"target":1187},{"edgeType":"contains","source":1985,"target":2299},{"edgeType":"contains","source":1472,"target":1554},{"edgeType":"calls","source":1846,"target":664},{"edgeType":"contains","source":46,"target":47},{"edgeType":"calls","source":2071,"target":1088},{"edgeType":"contains","source":135,"target":459},{"edgeType":"calls","source":2330,"target":2041},{"edgeType":"contains","source":1094,"target":1119},{"edgeType":"contains","source":1681,"target":1682},{"edgeType":"contains","source":1621,"target":1692},{"edgeType":"contains","source":1103,"target":1104},{"edgeType":"contains","source":137,"target":924},{"edgeType":"contains","source":1116,"target":2815},{"edgeType":"contains","source":3,"target":57},{"edgeType":"contains","source":473,"target":550},{"edgeType":"calls","source":1824,"target":1345},{"edgeType":"calls","source":1550,"target":326},{"edgeType":"contains","source":126,"target":1794},{"edgeType":"calls","source":1938,"target":982},{"edgeType":"calls","source":1783,"target":502},{"edgeType":"imports","source":1447,"target":1414},{"edgeType":"contains","source":1621,"target":1693},{"edgeType":"calls","source":2071,"target":1087},{"edgeType":"contains","source":135,"target":458},{"edgeType":"calls","source":2228,"target":976},{"edgeType":"calls","source":2059,"target":666},{"edgeType":"contains","source":219,"target":496},{"edgeType":"imports","source":1234,"target":2468},{"edgeType":"contains","source":980,"target":2802},{"edgeType":"contains","source":430,"target":2147},{"edgeType":"contains","source":980,"target":2806},{"edgeType":"calls","source":1867,"target":1857},{"edgeType":"calls","source":1900,"target":1891},{"edgeType":"contains","source":137,"target":927},{"edgeType":"contains","source":1116,"target":2818},{"edgeType":"contains","source":25,"target":1492},{"edgeType":"calls","source":1930,"target":1225},{"edgeType":"calls","source":2071,"target":1082},{"edgeType":"calls","source":134,"target":878},{"edgeType":"imports","source":57,"target":107},{"edgeType":"contains","source":858,"target":1038},{"edgeType":"calls","source":1899,"target":1393},{"edgeType":"contains","source":135,"target":461},{"edgeType":"calls","source":1802,"target":700},{"edgeType":"contains","source":1378,"target":1832},{"edgeType":"contains","source":473,"target":553},{"edgeType":"contains","source":450,"target":473},{"edgeType":"contains","source":1472,"target":1825},{"edgeType":"contains","source":980,"target":2805},{"edgeType":"calls","source":2076,"target":662},{"edgeType":"contains","source":473,"target":552},{"edgeType":"contains","source":137,"target":926},{"edgeType":"contains","source":1684,"target":1860},{"edgeType":"calls","source":2008,"target":1977},{"edgeType":"contains","source":2540,"target":2543},{"edgeType":"calls","source":2071,"target":288},{"edgeType":"contains","source":443,"target":953},{"edgeType":"contains","source":219,"target":498},{"edgeType":"calls","source":2424,"target":976},{"edgeType":"calls","source":1595,"target":1038},{"edgeType":"contains","source":1482,"target":1516},{"edgeType":"contains","source":1472,"target":1826},{"edgeType":"contains","source":305,"target":739},{"edgeType":"calls","source":1867,"target":1859},{"edgeType":"contains","source":1414,"target":1506},{"edgeType":"calls","source":1783,"target":499},{"edgeType":"imports","source":1078,"target":1222},{"edgeType":"calls","source":1930,"target":2020},{"edgeType":"calls","source":1528,"target":476},{"edgeType":"contains","source":137,"target":929},{"edgeType":"calls","source":1930,"target":1227},{"edgeType":"contains","source":1,"target":124},{"edgeType":"contains","source":147,"target":884},{"edgeType":"calls","source":2008,"target":1980},{"edgeType":"calls","source":2330,"target":451},{"edgeType":"calls","source":2071,"target":1084},{"edgeType":"contains","source":975,"target":1377},{"edgeType":"contains","source":427,"target":1188},{"edgeType":"contains","source":2160,"target":2164},{"edgeType":"contains","source":219,"target":501},{"edgeType":"calls","source":2329,"target":2332},{"edgeType":"contains","source":473,"target":555},{"edgeType":"contains","source":352,"target":2192},{"edgeType":"calls","source":2615,"target":1394},{"edgeType":"calls","source":2775,"target":2776},{"edgeType":"calls","source":1900,"target":1892},{"edgeType":"contains","source":980,"target":2807},{"edgeType":"calls","source":1878,"target":460},{"edgeType":"calls","source":1867,"target":1858},{"edgeType":"calls","source":285,"target":690},{"edgeType":"calls","source":1107,"target":1106},{"edgeType":"contains","source":137,"target":928},{"edgeType":"calls","source":1930,"target":1226},{"edgeType":"calls","source":1810,"target":982},{"edgeType":"contains","source":2446,"target":2548},{"edgeType":"calls","source":452,"target":270},{"edgeType":"calls","source":2008,"target":1979},{"edgeType":"contains","source":2540,"target":2541},{"edgeType":"imports","source":1234,"target":879},{"edgeType":"calls","source":2071,"target":1083},{"edgeType":"contains","source":147,"target":883},{"edgeType":"calls","source":2792,"target":664},{"edgeType":"calls","source":1899,"target":1394},{"edgeType":"calls","source":1875,"target":288},{"edgeType":"contains","source":219,"target":500},{"edgeType":"contains","source":473,"target":554},{"edgeType":"contains","source":137,"target":931},{"edgeType":"contains","source":2540,"target":2546},{"edgeType":"contains","source":147,"target":886},{"edgeType":"contains","source":1,"target":126},{"edgeType":"calls","source":2015,"target":2021},{"edgeType":"contains","source":607,"target":631},{"edgeType":"calls","source":1426,"target":196},{"edgeType":"contains","source":1472,"target":1829},{"edgeType":"calls","source":2194,"target":2287},{"edgeType":"calls","source":2352,"target":296},{"edgeType":"calls","source":2253,"target":194},{"edgeType":"imports","source":427,"target":1863},{"edgeType":"contains","source":1794,"target":2418},{"edgeType":"contains","source":137,"target":930},{"edgeType":"contains","source":2375,"target":2377},{"edgeType":"contains","source":135,"target":2314},{"edgeType":"contains","source":147,"target":885},{"edgeType":"contains","source":1794,"target":2682},{"edgeType":"contains","source":981,"target":1192},{"edgeType":"contains","source":427,"target":2246},{"edgeType":"calls","source":1426,"target":195},{"edgeType":"calls","source":1792,"target":1798},{"edgeType":"contains","source":192,"target":282},{"edgeType":"contains","source":1031,"target":1756},{"edgeType":"calls","source":2685,"target":2658},{"edgeType":"calls","source":2615,"target":1393},{"edgeType":"calls","source":2429,"target":1081},{"edgeType":"calls","source":2257,"target":1124},{"edgeType":"contains","source":61,"target":118},{"edgeType":"calls","source":954,"target":296},{"edgeType":"contains","source":147,"target":888},{"edgeType":"calls","source":2008,"target":1976},{"edgeType":"contains","source":137,"target":933},{"edgeType":"contains","source":2441,"target":2442},{"edgeType":"calls","source":2330,"target":2297},{"edgeType":"calls","source":1955,"target":976},{"edgeType":"contains","source":11,"target":83},{"edgeType":"contains","source":1116,"target":1238},{"edgeType":"calls","source":2330,"target":976},{"edgeType":"calls","source":2458,"target":1236},{"edgeType":"contains","source":1794,"target":2680},{"edgeType":"contains","source":177,"target":1278},{"edgeType":"calls","source":2257,"target":1125},{"edgeType":"calls","source":2474,"target":476},{"edgeType":"calls","source":2008,"target":1975},{"edgeType":"calls","source":1504,"target":951},{"edgeType":"contains","source":147,"target":887},{"edgeType":"contains","source":137,"target":932},{"edgeType":"calls","source":1930,"target":429},{"edgeType":"contains","source":71,"target":72},{"edgeType":"contains","source":1111,"target":1128},{"edgeType":"calls","source":2600,"target":1063},{"edgeType":"contains","source":219,"target":504},{"edgeType":"calls","source":2672,"target":681},{"edgeType":"contains","source":1472,"target":1828},{"edgeType":"calls","source":1506,"target":1417},{"edgeType":"calls","source":1652,"target":326},{"edgeType":"calls","source":1802,"target":697},{"edgeType":"calls","source":1994,"target":290},{"edgeType":"contains","source":2540,"target":2550},{"edgeType":"contains","source":147,"target":890},{"edgeType":"calls","source":1793,"target":707},{"edgeType":"calls","source":285,"target":681},{"edgeType":"contains","source":1745,"target":2090},{"edgeType":"contains","source":255,"target":1241},{"edgeType":"contains","source":443,"target":698},{"edgeType":"calls","source":2672,"target":678},{"edgeType":"calls","source":2228,"target":2286},{"edgeType":"contains","source":1854,"target":2411},{"edgeType":"calls","source":2221,"target":2239},{"edgeType":"calls","source":1812,"target":1967},{"edgeType":"calls","source":2652,"target":241},{"edgeType":"contains","source":147,"target":889},{"edgeType":"contains","source":46,"target":1641},{"edgeType":"contains","source":1794,"target":2686},{"edgeType":"calls","source":1462,"target":1454},{"edgeType":"contains","source":137,"target":934},{"edgeType":"contains","source":219,"target":507},{"edgeType":"contains","source":219,"target":506},{"edgeType":"contains","source":202,"target":1033},{"edgeType":"calls","source":2330,"target":2296},{"edgeType":"contains","source":427,"target":2250},{"edgeType":"contains","source":430,"target":1100},{"edgeType":"contains","source":298,"target":964},{"edgeType":"contains","source":1854,"target":2412},{"edgeType":"contains","source":352,"target":2197},{"edgeType":"calls","source":2458,"target":1235},{"edgeType":"imports","source":1969,"target":1621},{"edgeType":"contains","source":996,"target":999},{"edgeType":"calls","source":2442,"target":670},{"edgeType":"contains","source":147,"target":892},{"edgeType":"contains","source":126,"target":1543},{"edgeType":"calls","source":2672,"target":675},{"edgeType":"contains","source":219,"target":510},{"edgeType":"calls","source":2019,"target":1895},{"edgeType":"contains","source":1794,"target":2683},{"edgeType":"contains","source":162,"target":163},{"edgeType":"contains","source":137,"target":938},{"edgeType":"contains","source":307,"target":1745},{"edgeType":"contains","source":2446,"target":1762},{"edgeType":"contains","source":1472,"target":1831},{"edgeType":"calls","source":1686,"target":326},{"edgeType":"calls","source":2228,"target":2284},{"edgeType":"calls","source":1238,"target":1529},{"edgeType":"contains","source":996,"target":998},{"edgeType":"contains","source":2540,"target":2549},{"edgeType":"contains","source":147,"target":891},{"edgeType":"calls","source":1930,"target":425},{"edgeType":"contains","source":219,"target":509},{"edgeType":"contains","source":137,"target":936},{"edgeType":"contains","source":1116,"target":2827},{"edgeType":"contains","source":137,"target":937},{"edgeType":"contains","source":1392,"target":1405},{"edgeType":"calls","source":2472,"target":1063},{"edgeType":"calls","source":1878,"target":451},{"edgeType":"contains","source":25,"target":445},{"edgeType":"contains","source":1013,"target":1263},{"edgeType":"contains","source":1854,"target":2410},{"edgeType":"contains","source":50,"target":991},{"edgeType":"calls","source":2651,"target":2649},{"edgeType":"calls","source":2672,"target":508},{"edgeType":"contains","source":1118,"target":1150},{"edgeType":"calls","source":2172,"target":681},{"edgeType":"calls","source":2145,"target":2311},{"edgeType":"calls","source":1308,"target":1303},{"edgeType":"contains","source":430,"target":2130},{"edgeType":"contains","source":473,"target":532},{"edgeType":"calls","source":2812,"target":2775},{"edgeType":"contains","source":137,"target":907},{"edgeType":"contains","source":1222,"target":2419},{"edgeType":"contains","source":306,"target":424},{"edgeType":"contains","source":1118,"target":1149},{"edgeType":"calls","source":2232,"target":1200},{"edgeType":"calls","source":2377,"target":669},{"edgeType":"calls","source":1627,"target":662},{"edgeType":"calls","source":2077,"target":982},{"edgeType":"calls","source":2228,"target":2117},{"edgeType":"contains","source":1435,"target":309},{"edgeType":"calls","source":2663,"target":2638},{"edgeType":"contains","source":430,"target":2129},{"edgeType":"calls","source":1192,"target":670},{"edgeType":"calls","source":1961,"target":878},{"edgeType":"calls","source":2546,"target":1244},{"edgeType":"contains","source":513,"target":613},{"edgeType":"calls","source":1308,"target":1302},{"edgeType":"calls","source":2154,"target":976},{"edgeType":"contains","source":1116,"target":2796},{"edgeType":"contains","source":137,"target":906},{"edgeType":"contains","source":473,"target":531},{"edgeType":"contains","source":1,"target":101},{"edgeType":"contains","source":65,"target":1288},{"edgeType":"contains","source":438,"target":1352},{"edgeType":"calls","source":134,"target":700},{"edgeType":"calls","source":1763,"target":1202},{"edgeType":"contains","source":202,"target":1533},{"edgeType":"calls","source":2232,"target":1201},{"edgeType":"contains","source":74,"target":1273},{"edgeType":"contains","source":1118,"target":1148},{"edgeType":"calls","source":2196,"target":1256},{"edgeType":"calls","source":2226,"target":326},{"edgeType":"calls","source":1789,"target":664},{"edgeType":"contains","source":1119,"target":1121},{"edgeType":"contains","source":1118,"target":1152},{"edgeType":"contains","source":1185,"target":1189},{"edgeType":"contains","source":127,"target":954},{"edgeType":"contains","source":607,"target":609},{"edgeType":"calls","source":1308,"target":1305},{"edgeType":"contains","source":430,"target":2132},{"edgeType":"contains","source":137,"target":909},{"edgeType":"calls","source":442,"target":668},{"edgeType":"calls","source":2827,"target":194},{"edgeType":"contains","source":1222,"target":2417},{"edgeType":"contains","source":306,"target":426},{"edgeType":"contains","source":980,"target":1994},{"edgeType":"contains","source":1985,"target":2019},{"edgeType":"contains","source":473,"target":534},{"edgeType":"contains","source":1961,"target":1970},{"edgeType":"contains","source":1836,"target":2146},{"edgeType":"contains","source":1119,"target":1120},{"edgeType":"contains","source":1118,"target":1151},{"edgeType":"calls","source":1511,"target":296},{"edgeType":"contains","source":147,"target":862},{"edgeType":"calls","source":2077,"target":984},{"edgeType":"contains","source":302,"target":1078},{"edgeType":"contains","source":513,"target":615},{"edgeType":"calls","source":1308,"target":1304},{"edgeType":"calls","source":164,"target":300},{"edgeType":"contains","source":430,"target":2131},{"edgeType":"calls","source":1426,"target":288},{"edgeType":"calls","source":1516,"target":669},{"edgeType":"contains","source":137,"target":908},{"edgeType":"calls","source":2263,"target":502},{"edgeType":"contains","source":473,"target":533},{"edgeType":"contains","source":1721,"target":2012},{"edgeType":"calls","source":2687,"target":2685},{"edgeType":"contains","source":858,"target":1022},{"edgeType":"contains","source":513,"target":618},{"edgeType":"contains","source":1985,"target":2289},{"edgeType":"contains","source":1118,"target":1154},{"edgeType":"calls","source":1514,"target":1519},{"edgeType":"calls","source":1821,"target":194},{"edgeType":"contains","source":473,"target":537},{"edgeType":"calls","source":1429,"target":1776},{"edgeType":"contains","source":2077,"target":2080},{"edgeType":"contains","source":1721,"target":2017},{"edgeType":"calls","source":164,"target":295},{"edgeType":"contains","source":473,"target":536},{"edgeType":"calls","source":1942,"target":1728},{"edgeType":"contains","source":137,"target":911},{"edgeType":"contains","source":303,"target":1578},{"edgeType":"contains","source":2075,"target":2406},{"edgeType":"calls","source":2662,"target":2664},{"edgeType":"calls","source":2263,"target":499},{"edgeType":"calls","source":2629,"target":2630},{"edgeType":"calls","source":442,"target":662},{"edgeType":"calls","source":1949,"target":982},{"edgeType":"contains","source":147,"target":864},{"edgeType":"contains","source":513,"target":617},{"edgeType":"contains","source":1118,"target":1153},{"edgeType":"calls","source":1633,"target":1529},{"edgeType":"calls","source":2672,"target":505},{"edgeType":"contains","source":1985,"target":2290},{"edgeType":"calls","source":1514,"target":1518},{"edgeType":"calls","source":1188,"target":1054},{"edgeType":"calls","source":2172,"target":678},{"edgeType":"contains","source":1031,"target":2000},{"edgeType":"calls","source":2064,"target":1909},{"edgeType":"calls","source":164,"target":294},{"edgeType":"contains","source":1414,"target":1493},{"edgeType":"calls","source":1869,"target":1876},{"edgeType":"contains","source":137,"target":910},{"edgeType":"contains","source":473,"target":535},{"edgeType":"calls","source":2036,"target":1191},{"edgeType":"contains","source":11,"target":62},{"edgeType":"contains","source":513,"target":620},{"edgeType":"contains","source":430,"target":2136},{"edgeType":"contains","source":975,"target":1361},{"edgeType":"calls","source":1308,"target":1301},{"edgeType":"contains","source":473,"target":539},{"edgeType":"calls","source":2452,"target":187},{"edgeType":"contains","source":255,"target":1219},{"edgeType":"calls","source":2377,"target":662},{"edgeType":"contains","source":219,"target":221},{"edgeType":"calls","source":2172,"target":675},{"edgeType":"contains","source":1222,"target":2421},{"edgeType":"contains","source":137,"target":913},{"edgeType":"contains","source":2075,"target":2404},{"edgeType":"calls","source":1243,"target":673},{"edgeType":"calls","source":1763,"target":1201},{"edgeType":"contains","source":147,"target":867},{"edgeType":"calls","source":134,"target":697},{"edgeType":"calls","source":2401,"target":976},{"edgeType":"calls","source":1788,"target":690},{"edgeType":"contains","source":1118,"target":1155},{"edgeType":"calls","source":2672,"target":503},{"edgeType":"calls","source":1949,"target":984},{"edgeType":"contains","source":473,"target":538},{"edgeType":"contains","source":1472,"target":2071},{"edgeType":"calls","source":2614,"target":451},{"edgeType":"contains","source":1222,"target":2422},{"edgeType":"contains","source":352,"target":2174},{"edgeType":"calls","source":1763,"target":1200},{"edgeType":"contains","source":92,"target":193},{"edgeType":"contains","source":2137,"target":2333},{"edgeType":"contains","source":137,"target":912},{"edgeType":"contains","source":2075,"target":2405},{"edgeType":"calls","source":2733,"target":462},{"edgeType":"imports","source":76,"target":108},{"edgeType":"contains","source":513,"target":622},{"edgeType":"calls","source":1311,"target":673},{"edgeType":"calls","source":1596,"target":1087},{"edgeType":"contains","source":1222,"target":2427},{"edgeType":"calls","source":1352,"target":195},{"edgeType":"contains","source":473,"target":541},{"edgeType":"imports","source":1447,"target":1475},{"edgeType":"contains","source":303,"target":1582},{"edgeType":"calls","source":1272,"target":296},{"edgeType":"imports","source":1836,"target":251},{"edgeType":"contains","source":137,"target":915},{"edgeType":"calls","source":1173,"target":194},{"edgeType":"contains","source":200,"target":283},{"edgeType":"contains","source":147,"target":869},{"edgeType":"calls","source":1191,"target":429},{"edgeType":"calls","source":2242,"target":2203},{"edgeType":"calls","source":2620,"target":2377},{"edgeType":"contains","source":1985,"target":2294},{"edgeType":"calls","source":1899,"target":678},{"edgeType":"contains","source":513,"target":621},{"edgeType":"contains","source":473,"target":540},{"edgeType":"contains","source":1794,"target":2401},{"edgeType":"calls","source":2452,"target":186},{"edgeType":"calls","source":1596,"target":1086},{"edgeType":"contains","source":121,"target":2203},{"edgeType":"calls","source":2679,"target":2662},{"edgeType":"calls","source":2429,"target":2485},{"edgeType":"contains","source":137,"target":914},{"edgeType":"contains","source":1794,"target":2666},{"edgeType":"contains","source":2441,"target":2428},{"edgeType":"calls","source":2733,"target":460},{"edgeType":"calls","source":2217,"target":1918},{"edgeType":"calls","source":316,"target":337},{"edgeType":"contains","source":513,"target":624},{"edgeType":"imports","source":1113,"target":463},{"edgeType":"contains","source":1985,"target":2291},{"edgeType":"calls","source":2588,"target":195},{"edgeType":"calls","source":1596,"target":1089},{"edgeType":"calls","source":2764,"target":288},{"edgeType":"calls","source":1429,"target":1774},{"edgeType":"calls","source":1899,"target":681},{"edgeType":"calls","source":977,"target":194},{"edgeType":"contains","source":1222,"target":2425},{"edgeType":"contains","source":473,"target":543},{"edgeType":"contains","source":1543,"target":1723},{"edgeType":"imports","source":1836,"target":513},{"edgeType":"calls","source":2664,"target":1539},{"edgeType":"calls","source":1426,"target":1602},{"edgeType":"contains","source":352,"target":858},{"edgeType":"contains","source":25,"target":1218},{"edgeType":"contains","source":147,"target":871},{"edgeType":"contains","source":1113,"target":2900},{"edgeType":"contains","source":137,"target":917},{"edgeType":"calls","source":1516,"target":662},{"edgeType":"calls","source":1528,"target":290},{"edgeType":"contains","source":2075,"target":2408},{"edgeType":"calls","source":2827,"target":2828},{"edgeType":"imports","source":76,"target":107},{"edgeType":"calls","source":316,"target":336},{"edgeType":"calls","source":2363,"target":300},{"edgeType":"contains","source":1639,"target":1655},{"edgeType":"calls","source":1596,"target":1088},{"edgeType":"calls","source":2588,"target":196},{"edgeType":"calls","source":2059,"target":2062},{"edgeType":"calls","source":1352,"target":196},{"edgeType":"contains","source":473,"target":542},{"edgeType":"contains","source":1472,"target":1811},{"edgeType":"contains","source":87,"target":88},{"edgeType":"calls","source":1426,"target":1601},{"edgeType":"contains","source":50,"target":178},{"edgeType":"calls","source":2452,"target":184},{"edgeType":"contains","source":88,"target":1378},{"edgeType":"contains","source":137,"target":916},{"edgeType":"contains","source":2075,"target":2409},{"edgeType":"calls","source":1550,"target":664},{"edgeType":"contains","source":1031,"target":1477},{"edgeType":"calls","source":134,"target":958},{"edgeType":"calls","source":1899,"target":675},{"edgeType":"calls","source":1191,"target":425},{"edgeType":"calls","source":2818,"target":462},{"edgeType":"calls","source":1311,"target":669},{"edgeType":"contains","source":473,"target":545},{"edgeType":"calls","source":1016,"target":300},{"edgeType":"calls","source":1596,"target":1083},{"edgeType":"contains","source":1222,"target":2167},{"edgeType":"calls","source":2072,"target":1125},{"edgeType":"contains","source":147,"target":873},{"edgeType":"contains","source":1621,"target":1690},{"edgeType":"imports","source":980,"target":91},{"edgeType":"contains","source":1116,"target":2809},{"edgeType":"contains","source":1794,"target":2669},{"edgeType":"contains","source":137,"target":919},{"edgeType":"calls","source":1039,"target":1173},{"edgeType":"contains","source":219,"target":491},{"edgeType":"contains","source":1045,"target":1046},{"edgeType":"calls","source":1522,"target":1526},{"edgeType":"calls","source":2097,"target":878},{"edgeType":"calls","source":2572,"target":690},{"edgeType":"calls","source":1804,"target":976},{"edgeType":"imports","source":1447,"target":1734},{"edgeType":"contains","source":473,"target":544},{"edgeType":"contains","source":1985,"target":2298},{"edgeType":"calls","source":1596,"target":1082},{"edgeType":"calls","source":1352,"target":982},{"edgeType":"calls","source":1899,"target":1202},{"edgeType":"calls","source":2072,"target":1124},{"edgeType":"contains","source":513,"target":625},{"edgeType":"imports","source":1969,"target":879},{"edgeType":"contains","source":126,"target":202},{"edgeType":"contains","source":137,"target":918},{"edgeType":"contains","source":1621,"target":1691},{"edgeType":"contains","source":137,"target":921},{"edgeType":"contains","source":1116,"target":2812},{"edgeType":"calls","source":2818,"target":460},{"edgeType":"contains","source":1,"target":116},{"edgeType":"calls","source":2325,"target":680},{"edgeType":"contains","source":473,"target":547},{"edgeType":"contains","source":1985,"target":2295},{"edgeType":"contains","source":19,"target":1672},{"edgeType":"contains","source":1639,"target":1658},{"edgeType":"calls","source":134,"target":690},{"edgeType":"contains","source":2160,"target":2155},{"edgeType":"calls","source":1190,"target":194},{"edgeType":"calls","source":1596,"target":1085},{"edgeType":"calls","source":2189,"target":1197},{"edgeType":"calls","source":1770,"target":976},{"edgeType":"calls","source":2199,"target":1944},{"edgeType":"contains","source":147,"target":875},{"edgeType":"calls","source":2818,"target":196},{"edgeType":"contains","source":980,"target":2799},{"edgeType":"contains","source":1116,"target":2811},{"edgeType":"contains","source":1794,"target":2667},{"edgeType":"contains","source":473,"target":546},{"edgeType":"calls","source":1122,"target":451},{"edgeType":"calls","source":1596,"target":1084},{"edgeType":"calls","source":1352,"target":984},{"edgeType":"calls","source":1157,"target":951},{"edgeType":"calls","source":2199,"target":1945},{"edgeType":"contains","source":2036,"target":2037},{"edgeType":"calls","source":1788,"target":681},{"edgeType":"contains","source":513,"target":627},{"edgeType":"contains","source":137,"target":920},{"edgeType":"contains","source":137,"target":890},{"edgeType":"contains","source":2137,"target":463},{"edgeType":"calls","source":1278,"target":664},{"edgeType":"contains","source":2877,"target":2892},{"edgeType":"contains","source":306,"target":408},{"edgeType":"contains","source":1721,"target":1996},{"edgeType":"calls","source":1326,"target":1290},{"edgeType":"calls","source":1875,"target":1976},{"edgeType":"contains","source":177,"target":179},{"edgeType":"imports","source":303,"target":446},{"edgeType":"contains","source":1118,"target":1133},{"edgeType":"contains","source":2551,"target":2428},{"edgeType":"calls","source":2816,"target":1082},{"edgeType":"contains","source":1721,"target":1732},{"edgeType":"calls","source":1848,"target":1227},{"edgeType":"contains","source":137,"target":889},{"edgeType":"contains","source":1762,"target":1783},{"edgeType":"contains","source":306,"target":407},{"edgeType":"calls","source":1942,"target":1748},{"edgeType":"calls","source":1875,"target":1975},{"edgeType":"calls","source":1326,"target":1289},{"edgeType":"contains","source":1118,"target":1132},{"edgeType":"calls","source":2816,"target":1083},{"edgeType":"contains","source":1222,"target":1875},{"edgeType":"contains","source":2877,"target":2893},{"edgeType":"contains","source":1472,"target":2317},{"edgeType":"contains","source":114,"target":1338},{"edgeType":"contains","source":513,"target":596},{"edgeType":"imports","source":457,"target":429},{"edgeType":"calls","source":1525,"target":669},{"edgeType":"contains","source":1713,"target":1717},{"edgeType":"contains","source":25,"target":133},{"edgeType":"calls","source":1848,"target":1226},{"edgeType":"calls","source":2134,"target":556},{"edgeType":"contains","source":1501,"target":1943},{"edgeType":"contains","source":126,"target":176},{"edgeType":"contains","source":137,"target":892},{"edgeType":"calls","source":1380,"target":675},{"edgeType":"contains","source":1,"target":87},{"edgeType":"contains","source":306,"target":410},{"edgeType":"contains","source":473,"target":518},{"edgeType":"contains","source":202,"target":1520},{"edgeType":"calls","source":1740,"target":878},{"edgeType":"contains","source":2877,"target":2890},{"edgeType":"calls","source":1292,"target":1289},{"edgeType":"imports","source":1447,"target":1448},{"edgeType":"contains","source":1118,"target":1135},{"edgeType":"contains","source":127,"target":674},{"edgeType":"contains","source":180,"target":880},{"edgeType":"calls","source":1418,"target":1082},{"edgeType":"contains","source":1713,"target":1714},{"edgeType":"contains","source":1176,"target":1715},{"edgeType":"calls","source":1312,"target":1197},{"edgeType":"contains","source":2137,"target":2311},{"edgeType":"calls","source":2019,"target":2006},{"edgeType":"calls","source":1532,"target":1512},{"edgeType":"contains","source":137,"target":891},{"edgeType":"contains","source":307,"target":1435},{"edgeType":"contains","source":19,"target":1642},{"edgeType":"contains","source":2877,"target":2891},{"edgeType":"contains","source":306,"target":409},{"edgeType":"contains","source":1721,"target":1995},{"edgeType":"contains","source":1,"target":350},{"edgeType":"contains","source":1472,"target":2315},{"edgeType":"contains","source":2192,"target":2193},{"edgeType":"contains","source":1118,"target":1134},{"edgeType":"calls","source":1875,"target":1977},{"edgeType":"calls","source":2621,"target":1312},{"edgeType":"calls","source":1377,"target":502},{"edgeType":"imports","source":1234,"target":123},{"edgeType":"calls","source":1994,"target":666},{"edgeType":"calls","source":1405,"target":1220},{"edgeType":"calls","source":1312,"target":1196},{"edgeType":"calls","source":1848,"target":1228},{"edgeType":"calls","source":2096,"target":675},{"edgeType":"contains","source":513,"target":598},{"edgeType":"contains","source":177,"target":1504},{"edgeType":"contains","source":2011,"target":1202},{"edgeType":"contains","source":972,"target":1171},{"edgeType":"contains","source":473,"target":520},{"edgeType":"contains","source":137,"target":894},{"edgeType":"contains","source":202,"target":1522},{"edgeType":"calls","source":1404,"target":1246},{"edgeType":"contains","source":306,"target":412},{"edgeType":"calls","source":1380,"target":669},{"edgeType":"contains","source":1,"target":89},{"edgeType":"contains","source":1472,"target":2320},{"edgeType":"calls","source":2258,"target":670},{"edgeType":"contains","source":268,"target":269},{"edgeType":"contains","source":513,"target":601},{"edgeType":"contains","source":1118,"target":1137},{"edgeType":"contains","source":981,"target":1420},{"edgeType":"calls","source":1785,"target":1855},{"edgeType":"contains","source":2877,"target":2896},{"edgeType":"contains","source":1259,"target":1260},{"edgeType":"contains","source":1721,"target":2001},{"edgeType":"contains","source":306,"target":411},{"edgeType":"contains","source":473,"target":519},{"edgeType":"contains","source":2137,"target":2318},{"edgeType":"contains","source":1472,"target":2321},{"edgeType":"calls","source":2168,"target":290},{"edgeType":"contains","source":2877,"target":2897},{"edgeType":"calls","source":2010,"target":164},{"edgeType":"contains","source":981,"target":1419},{"edgeType":"calls","source":2018,"target":2030},{"edgeType":"calls","source":1097,"target":984},{"edgeType":"calls","source":1353,"target":976},{"edgeType":"contains","source":305,"target":706},{"edgeType":"contains","source":1482,"target":1483},{"edgeType":"imports","source":457,"target":425},{"edgeType":"calls","source":1438,"target":1512},{"edgeType":"calls","source":1596,"target":1899},{"edgeType":"contains","source":843,"target":944},{"edgeType":"calls","source":1968,"target":1734},{"edgeType":"contains","source":306,"target":414},{"edgeType":"contains","source":1985,"target":2006},{"edgeType":"contains","source":2011,"target":1200},{"edgeType":"imports","source":1447,"target":1972},{"edgeType":"imports","source":114,"target":1013},{"edgeType":"contains","source":126,"target":180},{"edgeType":"contains","source":137,"target":896},{"edgeType":"calls","source":2097,"target":1695},{"edgeType":"contains","source":513,"target":603},{"edgeType":"contains","source":126,"target":1501},{"edgeType":"contains","source":430,"target":2119},{"edgeType":"calls","source":2818,"target":2335},{"edgeType":"contains","source":1118,"target":1139},{"edgeType":"calls","source":1377,"target":499},{"edgeType":"contains","source":2877,"target":2894},{"edgeType":"calls","source":1848,"target":1225},{"edgeType":"imports","source":1447,"target":123},{"edgeType":"contains","source":305,"target":709},{"edgeType":"contains","source":981,"target":1422},{"edgeType":"contains","source":473,"target":522},{"edgeType":"contains","source":1794,"target":2378},{"edgeType":"contains","source":2011,"target":1201},{"edgeType":"contains","source":137,"target":895},{"edgeType":"contains","source":306,"target":413},{"edgeType":"calls","source":1895,"target":296},{"edgeType":"contains","source":311,"target":1051},{"edgeType":"calls","source":2353,"target":1688},{"edgeType":"contains","source":11,"target":45},{"edgeType":"contains","source":2877,"target":2895},{"edgeType":"calls","source":1785,"target":1856},{"edgeType":"contains","source":1118,"target":1138},{"edgeType":"imports","source":1234,"target":119},{"edgeType":"imports","source":1234,"target":1176},{"edgeType":"calls","source":1899,"target":700},{"edgeType":"calls","source":1900,"target":669},{"edgeType":"calls","source":1157,"target":976},{"edgeType":"calls","source":2679,"target":2681},{"edgeType":"contains","source":981,"target":1421},{"edgeType":"calls","source":2253,"target":296},{"edgeType":"contains","source":473,"target":521},{"edgeType":"calls","source":1115,"target":164},{"edgeType":"calls","source":2663,"target":1063},{"edgeType":"contains","source":126,"target":972},{"edgeType":"contains","source":152,"target":169},{"edgeType":"calls","source":2354,"target":1125},{"edgeType":"contains","source":1721,"target":2004},{"edgeType":"calls","source":1525,"target":662},{"edgeType":"contains","source":306,"target":416},{"edgeType":"calls","source":1834,"target":1125},{"edgeType":"calls","source":2287,"target":1088},{"edgeType":"contains","source":1472,"target":1531},{"edgeType":"contains","source":137,"target":898},{"edgeType":"calls","source":1426,"target":296},{"edgeType":"calls","source":134,"target":973},{"edgeType":"contains","source":430,"target":2121},{"edgeType":"contains","source":465,"target":1036},{"edgeType":"calls","source":2615,"target":2548},{"edgeType":"calls","source":2887,"target":194},{"edgeType":"calls","source":2096,"target":666},{"edgeType":"contains","source":176,"target":1803},{"edgeType":"contains","source":513,"target":605},{"edgeType":"calls","source":1669,"target":1483},{"edgeType":"contains","source":1118,"target":1141},{"edgeType":"contains","source":1639,"target":1640},{"edgeType":"contains","source":473,"target":524},{"edgeType":"contains","source":1259,"target":1264},{"edgeType":"calls","source":2429,"target":122},{"edgeType":"calls","source":1870,"target":1858},{"edgeType":"contains","source":6,"target":467},{"edgeType":"calls","source":2172,"target":690},{"edgeType":"contains","source":306,"target":415},{"edgeType":"calls","source":2287,"target":1089},{"edgeType":"contains","source":843,"target":945},{"edgeType":"contains","source":60,"target":113},{"edgeType":"calls","source":1834,"target":1124},{"edgeType":"calls","source":2149,"target":2196},{"edgeType":"contains","source":137,"target":897},{"edgeType":"contains","source":1,"target":92},{"edgeType":"calls","source":2087,"target":680},{"edgeType":"calls","source":2733,"target":476},{"edgeType":"contains","source":2075,"target":2395},{"edgeType":"calls","source":2169,"target":2105},{"edgeType":"calls","source":1398,"target":1162},{"edgeType":"calls","source":2623,"target":451},{"edgeType":"contains","source":473,"target":523},{"edgeType":"calls","source":2745,"target":2747},{"edgeType":"contains","source":121,"target":2186},{"edgeType":"imports","source":1447,"target":665},{"edgeType":"contains","source":1854,"target":2375},{"edgeType":"calls","source":1870,"target":1857},{"edgeType":"contains","source":1,"target":1681},{"edgeType":"calls","source":1308,"target":1313},{"edgeType":"calls","source":2287,"target":1086},{"edgeType":"contains","source":1943,"target":1991},{"edgeType":"calls","source":2316,"target":1244},{"edgeType":"calls","source":2060,"target":1256},{"edgeType":"contains","source":137,"target":900},{"edgeType":"contains","source":1116,"target":2791},{"edgeType":"calls","source":2600,"target":1161},{"edgeType":"contains","source":1836,"target":1873},{"edgeType":"contains","source":2877,"target":2898},{"edgeType":"calls","source":1299,"target":1063},{"edgeType":"imports","source":1447,"target":1985},{"edgeType":"contains","source":1513,"target":1580},{"edgeType":"contains","source":1118,"target":1143},{"edgeType":"calls","source":1899,"target":697},{"edgeType":"contains","source":175,"target":515},{"edgeType":"contains","source":1259,"target":1262},{"edgeType":"contains","source":6,"target":469},{"edgeType":"contains","source":306,"target":418},{"edgeType":"contains","source":473,"target":526},{"edgeType":"calls","source":1749,"target":326},{"edgeType":"calls","source":2354,"target":1124},{"edgeType":"contains","source":306,"target":417},{"edgeType":"imports","source":1794,"target":1797},{"edgeType":"contains","source":1794,"target":2647},{"edgeType":"calls","source":2251,"target":2203},{"edgeType":"calls","source":2287,"target":1087},{"edgeType":"contains","source":137,"target":899},{"edgeType":"calls","source":1380,"target":666},{"edgeType":"contains","source":2877,"target":2899},{"edgeType":"contains","source":2250,"target":2253},{"edgeType":"calls","source":2600,"target":1162},{"edgeType":"calls","source":2332,"target":2335},{"edgeType":"contains","source":430,"target":2122},{"edgeType":"contains","source":465,"target":1037},{"edgeType":"calls","source":1097,"target":982},{"edgeType":"contains","source":1118,"target":1142},{"edgeType":"calls","source":1408,"target":326},{"edgeType":"contains","source":175,"target":514},{"edgeType":"calls","source":1870,"target":1859},{"edgeType":"calls","source":2679,"target":2677},{"edgeType":"contains","source":473,"target":525},{"edgeType":"calls","source":1308,"target":1307},{"edgeType":"calls","source":2253,"target":288},{"edgeType":"contains","source":1028,"target":1029},{"edgeType":"calls","source":1477,"target":296},{"edgeType":"calls","source":2792,"target":2077},{"edgeType":"calls","source":2287,"target":1084},{"edgeType":"contains","source":11,"target":1637},{"edgeType":"calls","source":2338,"target":296},{"edgeType":"contains","source":1794,"target":2652},{"edgeType":"contains","source":137,"target":902},{"edgeType":"contains","source":260,"target":261},{"edgeType":"calls","source":1462,"target":1289},{"edgeType":"calls","source":449,"target":453},{"edgeType":"contains","source":1721,"target":2009},{"edgeType":"contains","source":1118,"target":1145},{"edgeType":"calls","source":2154,"target":451},{"edgeType":"contains","source":473,"target":528},{"edgeType":"contains","source":306,"target":420},{"edgeType":"calls","source":1932,"target":1253},{"edgeType":"calls","source":1736,"target":194},{"edgeType":"calls","source":1308,"target":1306},{"edgeType":"contains","source":1969,"target":1985},{"edgeType":"contains","source":1794,"target":2389},{"edgeType":"calls","source":2287,"target":1085},{"edgeType":"contains","source":165,"target":1355},{"edgeType":"contains","source":135,"target":2285},{"edgeType":"calls","source":2818,"target":215},{"edgeType":"calls","source":1320,"target":670},{"edgeType":"contains","source":137,"target":901},{"edgeType":"contains","source":1116,"target":2792},{"edgeType":"calls","source":2172,"target":2272},{"edgeType":"calls","source":1899,"target":690},{"edgeType":"calls","source":1796,"target":976},{"edgeType":"contains","source":513,"target":608},{"edgeType":"contains","source":1222,"target":2416},{"edgeType":"contains","source":2075,"target":2399},{"edgeType":"contains","source":175,"target":516},{"edgeType":"contains","source":1118,"target":1144},{"edgeType":"contains","source":306,"target":419},{"edgeType":"contains","source":473,"target":527},{"edgeType":"imports","source":1113,"target":709},{"edgeType":"calls","source":2452,"target":195},{"edgeType":"contains","source":135,"target":2288},{"edgeType":"imports","source":1969,"target":861},{"edgeType":"calls","source":2287,"target":1082},{"edgeType":"calls","source":1627,"target":669},{"edgeType":"calls","source":1952,"target":1957},{"edgeType":"contains","source":137,"target":905},{"edgeType":"calls","source":1324,"target":1341},{"edgeType":"calls","source":2079,"target":1191},{"edgeType":"calls","source":2096,"target":664},{"edgeType":"contains","source":473,"target":530},{"edgeType":"calls","source":134,"target":971},{"edgeType":"calls","source":1380,"target":662},{"edgeType":"calls","source":1398,"target":1161},{"edgeType":"calls","source":1900,"target":662},{"edgeType":"imports","source":1113,"target":706},{"edgeType":"contains","source":1222,"target":2413},{"edgeType":"calls","source":2232,"target":1202},{"edgeType":"contains","source":1118,"target":1147},{"edgeType":"calls","source":2452,"target":196},{"edgeType":"contains","source":1721,"target":2007},{"edgeType":"calls","source":1941,"target":976},{"edgeType":"contains","source":513,"target":611},{"edgeType":"calls","source":2019,"target":1729},{"edgeType":"calls","source":2287,"target":1083},{"edgeType":"contains","source":1501,"target":2221},{"edgeType":"contains","source":137,"target":903},{"edgeType":"contains","source":473,"target":529},{"edgeType":"calls","source":1462,"target":1290},{"edgeType":"contains","source":1118,"target":1146},{"edgeType":"contains","source":306,"target":421},{"edgeType":"calls","source":2681,"target":1253},{"edgeType":"calls","source":1024,"target":296},{"edgeType":"calls","source":2764,"target":1587},{"edgeType":"calls","source":1352,"target":170},{"edgeType":"contains","source":1297,"target":2439},{"edgeType":"contains","source":513,"target":581},{"edgeType":"contains","source":2563,"target":2568},{"edgeType":"calls","source":1319,"target":664},{"edgeType":"contains","source":137,"target":874},{"edgeType":"calls","source":2169,"target":477},{"edgeType":"contains","source":160,"target":161},{"edgeType":"calls","source":1942,"target":1699},{"edgeType":"contains","source":1448,"target":1458},{"edgeType":"contains","source":1985,"target":1988},{"edgeType":"contains","source":1513,"target":1557},{"edgeType":"calls","source":2818,"target":2820},{"edgeType":"contains","source":306,"target":391},{"edgeType":"contains","source":1407,"target":1408},{"edgeType":"calls","source":2813,"target":1918},{"edgeType":"calls","source":1360,"target":186},{"edgeType":"contains","source":6,"target":441},{"edgeType":"calls","source":2018,"target":664},{"edgeType":"calls","source":134,"target":666},{"edgeType":"contains","source":1897,"target":2074},{"edgeType":"calls","source":2764,"target":1588},{"edgeType":"contains","source":1111,"target":1597},{"edgeType":"contains","source":1297,"target":2440},{"edgeType":"contains","source":2563,"target":2569},{"edgeType":"contains","source":137,"target":872},{"edgeType":"calls","source":2664,"target":1253},{"edgeType":"calls","source":2683,"target":664},{"edgeType":"calls","source":2076,"target":451},{"edgeType":"calls","source":1931,"target":982},{"edgeType":"contains","source":11,"target":22},{"edgeType":"calls","source":2818,"target":2821},{"edgeType":"calls","source":2752,"target":2753},{"edgeType":"contains","source":119,"target":1959},{"edgeType":"calls","source":2751,"target":670},{"edgeType":"calls","source":2572,"target":666},{"edgeType":"calls","source":2588,"target":170},{"edgeType":"calls","source":2265,"target":1198},{"edgeType":"calls","source":1909,"target":1932},{"edgeType":"calls","source":1907,"target":1994},{"edgeType":"contains","source":114,"target":1853},{"edgeType":"calls","source":2008,"target":2034},{"edgeType":"calls","source":1079,"target":1236},{"edgeType":"contains","source":1472,"target":2033},{"edgeType":"calls","source":466,"target":155},{"edgeType":"contains","source":513,"target":583},{"edgeType":"contains","source":350,"target":351},{"edgeType":"imports","source":1969,"target":1435},{"edgeType":"contains","source":1513,"target":1555},{"edgeType":"calls","source":2169,"target":475},{"edgeType":"calls","source":2149,"target":2152},{"edgeType":"contains","source":1,"target":71},{"edgeType":"calls","source":2083,"target":2084},{"edgeType":"contains","source":1985,"target":1986},{"edgeType":"contains","source":306,"target":393},{"edgeType":"calls","source":2764,"target":1585},{"edgeType":"calls","source":2265,"target":1199},{"edgeType":"calls","source":1598,"target":1530},{"edgeType":"calls","source":2764,"target":1586},{"edgeType":"calls","source":1079,"target":1235},{"edgeType":"calls","source":1340,"target":1336},{"edgeType":"contains","source":2563,"target":2567},{"edgeType":"imports","source":980,"target":119},{"edgeType":"contains","source":1513,"target":1556},{"edgeType":"contains","source":127,"target":128},{"edgeType":"calls","source":1007,"target":296},{"edgeType":"contains","source":1448,"target":1457},{"edgeType":"calls","source":1931,"target":984},{"edgeType":"calls","source":2311,"target":2152},{"edgeType":"calls","source":1817,"target":290},{"edgeType":"calls","source":2025,"target":184},{"edgeType":"calls","source":1942,"target":1700},{"edgeType":"calls","source":1565,"target":1231},{"edgeType":"calls","source":1360,"target":187},{"edgeType":"contains","source":11,"target":24},{"edgeType":"calls","source":2818,"target":2819},{"edgeType":"contains","source":1222,"target":1861},{"edgeType":"contains","source":513,"target":585},{"edgeType":"contains","source":1052,"target":1053},{"edgeType":"contains","source":980,"target":2228},{"edgeType":"contains","source":1297,"target":2443},{"edgeType":"contains","source":2877,"target":2880},{"edgeType":"calls","source":112,"target":288},{"edgeType":"calls","source":1715,"target":1333},{"edgeType":"imports","source":1721,"target":1722},{"edgeType":"calls","source":1824,"target":1918},{"edgeType":"calls","source":2327,"target":1124},{"edgeType":"contains","source":1060,"target":1069},{"edgeType":"calls","source":1824,"target":1125},{"edgeType":"contains","source":1472,"target":2039},{"edgeType":"calls","source":1532,"target":664},{"edgeType":"calls","source":2072,"target":572},{"edgeType":"calls","source":2623,"target":669},{"edgeType":"calls","source":1756,"target":326},{"edgeType":"contains","source":306,"target":395},{"edgeType":"calls","source":1308,"target":1265},{"edgeType":"calls","source":1846,"target":707},{"edgeType":"calls","source":2764,"target":1583},{"edgeType":"calls","source":2685,"target":1918},{"edgeType":"imports","source":1078,"target":513},{"edgeType":"contains","source":2877,"target":2881},{"edgeType":"calls","source":2316,"target":673},{"edgeType":"calls","source":2327,"target":1125},{"edgeType":"contains","source":1985,"target":2257},{"edgeType":"contains","source":981,"target":1403},{"edgeType":"contains","source":1297,"target":2444},{"edgeType":"calls","source":1824,"target":1124},{"edgeType":"calls","source":1715,"target":1332},{"edgeType":"contains","source":176,"target":1517},{"edgeType":"contains","source":137,"target":877},{"edgeType":"calls","source":2169,"target":474},{"edgeType":"calls","source":2884,"target":2885},{"edgeType":"calls","source":2764,"target":1584},{"edgeType":"contains","source":513,"target":587},{"edgeType":"calls","source":2107,"target":2128},{"edgeType":"contains","source":1794,"target":2361},{"edgeType":"contains","source":1052,"target":1055},{"edgeType":"contains","source":427,"target":2196},{"edgeType":"contains","source":465,"target":1018},{"edgeType":"contains","source":2877,"target":2878},{"edgeType":"contains","source":2563,"target":2570},{"edgeType":"calls","source":2169,"target":1792},{"edgeType":"contains","source":121,"target":2169},{"edgeType":"calls","source":985,"target":974},{"edgeType":"imports","source":1854,"target":1297},{"edgeType":"calls","source":1942,"target":1697},{"edgeType":"imports","source":1447,"target":1758},{"edgeType":"calls","source":2572,"target":1455},{"edgeType":"contains","source":1316,"target":1324},{"edgeType":"contains","source":306,"target":397},{"edgeType":"contains","source":1411,"target":1550},{"edgeType":"calls","source":1159,"target":1394},{"edgeType":"calls","source":1360,"target":184},{"edgeType":"calls","source":2764,"target":1581},{"edgeType":"contains","source":1052,"target":1054},{"edgeType":"contains","source":6,"target":183},{"edgeType":"contains","source":513,"target":586},{"edgeType":"contains","source":1113,"target":2334},{"edgeType":"imports","source":1794,"target":513},{"edgeType":"contains","source":11,"target":292},{"edgeType":"calls","source":2059,"target":976},{"edgeType":"calls","source":2072,"target":573},{"edgeType":"calls","source":2751,"target":664},{"edgeType":"calls","source":2572,"target":1456},{"edgeType":"calls","source":1159,"target":1393},{"edgeType":"contains","source":1,"target":74},{"edgeType":"contains","source":1721,"target":1983},{"edgeType":"calls","source":2635,"target":296},{"edgeType":"contains","source":2877,"target":2884},{"edgeType":"calls","source":2154,"target":669},{"edgeType":"calls","source":2085,"target":958},{"edgeType":"contains","source":1080,"target":1246},{"edgeType":"contains","source":513,"target":589},{"edgeType":"calls","source":1189,"target":194},{"edgeType":"calls","source":1517,"target":1125},{"edgeType":"calls","source":2669,"target":1088},{"edgeType":"calls","source":2084,"target":1253},{"edgeType":"calls","source":1715,"target":1329},{"edgeType":"calls","source":1360,"target":971},{"edgeType":"contains","source":306,"target":399},{"edgeType":"calls","source":2818,"target":2812},{"edgeType":"calls","source":1596,"target":1318},{"edgeType":"contains","source":119,"target":1968},{"edgeType":"calls","source":1888,"target":1515},{"edgeType":"contains","source":430,"target":1312},{"edgeType":"calls","source":2764,"target":1579},{"edgeType":"calls","source":1948,"target":976},{"edgeType":"imports","source":1234,"target":446},{"edgeType":"contains","source":1,"target":77},{"edgeType":"calls","source":1785,"target":1801},{"edgeType":"contains","source":101,"target":148},{"edgeType":"calls","source":2107,"target":2127},{"edgeType":"calls","source":2154,"target":670},{"edgeType":"calls","source":1715,"target":1328},{"edgeType":"contains","source":1052,"target":1056},{"edgeType":"calls","source":2818,"target":170},{"edgeType":"calls","source":1517,"target":1124},{"edgeType":"calls","source":2669,"target":1089},{"edgeType":"calls","source":1726,"target":194},{"edgeType":"calls","source":2672,"target":1261},{"edgeType":"calls","source":1596,"target":1317},{"edgeType":"imports","source":1113,"target":2877},{"edgeType":"calls","source":2429,"target":2452},{"edgeType":"calls","source":1380,"target":878},{"edgeType":"imports","source":1969,"target":1972},{"edgeType":"calls","source":1793,"target":1820},{"edgeType":"contains","source":2877,"target":2882},{"edgeType":"imports","source":1234,"target":709},{"edgeType":"calls","source":2120,"target":664},{"edgeType":"imports","source":1836,"target":1338},{"edgeType":"contains","source":216,"target":285},{"edgeType":"calls","source":2672,"target":2050},{"edgeType":"contains","source":1836,"target":1063},{"edgeType":"calls","source":2072,"target":570},{"edgeType":"contains","source":1794,"target":2365},{"edgeType":"calls","source":2669,"target":1086},{"edgeType":"contains","source":1,"target":607},{"edgeType":"contains","source":306,"target":402},{"edgeType":"calls","source":1360,"target":973},{"edgeType":"calls","source":1715,"target":1331},{"edgeType":"contains","source":119,"target":121},{"edgeType":"contains","source":306,"target":401},{"edgeType":"calls","source":2764,"target":1577},{"edgeType":"contains","source":87,"target":1113},{"edgeType":"contains","source":1472,"target":2306},{"edgeType":"contains","source":137,"target":884},{"edgeType":"contains","source":135,"target":2267},{"edgeType":"imports","source":114,"target":1868},{"edgeType":"contains","source":1335,"target":1532},{"edgeType":"contains","source":2877,"target":2883},{"edgeType":"contains","source":1176,"target":1178},{"edgeType":"imports","source":135,"target":425},{"edgeType":"contains","source":1080,"target":1247},{"edgeType":"calls","source":2350,"target":670},{"edgeType":"contains","source":430,"target":2106},{"edgeType":"contains","source":11,"target":32},{"edgeType":"calls","source":2669,"target":1087},{"edgeType":"calls","source":1715,"target":1330},{"edgeType":"calls","source":2287,"target":2359},{"edgeType":"contains","source":19,"target":48},{"edgeType":"calls","source":269,"target":439},{"edgeType":"contains","source":1683,"target":1051},{"edgeType":"contains","source":308,"target":338},{"edgeType":"contains","source":6,"target":1773},{"edgeType":"calls","source":2818,"target":2811},{"edgeType":"contains","source":137,"target":883},{"edgeType":"contains","source":1109,"target":1140},{"edgeType":"contains","source":176,"target":1791},{"edgeType":"calls","source":2246,"target":984},{"edgeType":"contains","source":1,"target":81},{"edgeType":"calls","source":1326,"target":1228},{"edgeType":"contains","source":121,"target":2175},{"edgeType":"contains","source":1118,"target":1129},{"edgeType":"calls","source":2672,"target":2048},{"edgeType":"contains","source":2877,"target":2888},{"edgeType":"contains","source":202,"target":1514},{"edgeType":"calls","source":2669,"target":1084},{"edgeType":"contains","source":308,"target":342},{"edgeType":"contains","source":306,"target":404},{"edgeType":"calls","source":2764,"target":1575},{"edgeType":"contains","source":2068,"target":2070},{"edgeType":"contains","source":1472,"target":2312},{"edgeType":"calls","source":1635,"target":1162},{"edgeType":"contains","source":513,"target":593},{"edgeType":"contains","source":114,"target":1863},{"edgeType":"contains","source":980,"target":2764},{"edgeType":"contains","source":137,"target":886},{"edgeType":"contains","source":2877,"target":2359},{"edgeType":"imports","source":76,"target":137},{"edgeType":"contains","source":19,"target":1636},{"edgeType":"imports","source":1969,"target":119},{"edgeType":"calls","source":2362,"target":296},{"edgeType":"contains","source":11,"target":34},{"edgeType":"contains","source":513,"target":592},{"edgeType":"calls","source":2022,"target":2113},{"edgeType":"calls","source":2025,"target":170},{"edgeType":"contains","source":308,"target":341},{"edgeType":"calls","source":1326,"target":1227},{"edgeType":"calls","source":2672,"target":2049},{"edgeType":"calls","source":2669,"target":1085},{"edgeType":"calls","source":2764,"target":1576},{"edgeType":"contains","source":114,"target":1334},{"edgeType":"imports","source":1447,"target":446},{"edgeType":"calls","source":1635,"target":1161},{"edgeType":"calls","source":2595,"target":1530},{"edgeType":"calls","source":2623,"target":662},{"edgeType":"contains","source":135,"target":2268},{"edgeType":"contains","source":1116,"target":2775},{"edgeType":"contains","source":137,"target":885},{"edgeType":"contains","source":457,"target":478},{"edgeType":"calls","source":2669,"target":1082},{"edgeType":"calls","source":1715,"target":1327},{"edgeType":"calls","source":1786,"target":976},{"edgeType":"calls","source":1600,"target":664},{"edgeType":"contains","source":1378,"target":1788},{"edgeType":"calls","source":2246,"target":982},{"edgeType":"contains","source":1794,"target":2369},{"edgeType":"contains","source":306,"target":406},{"edgeType":"calls","source":2557,"target":326},{"edgeType":"contains","source":1118,"target":1131},{"edgeType":"contains","source":1513,"target":1567},{"edgeType":"calls","source":2672,"target":2046},{"edgeType":"calls","source":2318,"target":1393},{"edgeType":"contains","source":1060,"target":1079},{"edgeType":"calls","source":2764,"target":1573},{"edgeType":"contains","source":135,"target":2271},{"edgeType":"contains","source":1794,"target":2370},{"edgeType":"contains","source":25,"target":132},{"edgeType":"imports","source":1836,"target":1863},{"edgeType":"contains","source":89,"target":262},{"edgeType":"calls","source":1943,"target":1129},{"edgeType":"contains","source":137,"target":888},{"edgeType":"imports","source":1234,"target":706},{"edgeType":"calls","source":2173,"target":2189},{"edgeType":"calls","source":341,"target":317},{"edgeType":"contains","source":74,"target":197},{"edgeType":"calls","source":1803,"target":976},{"edgeType":"contains","source":2877,"target":2887},{"edgeType":"calls","source":1438,"target":664},{"edgeType":"contains","source":1118,"target":1130},{"edgeType":"contains","source":308,"target":343},{"edgeType":"contains","source":306,"target":405},{"edgeType":"calls","source":2672,"target":2047},{"edgeType":"imports","source":1721,"target":1727},{"edgeType":"calls","source":2669,"target":1083},{"edgeType":"calls","source":1909,"target":1918},{"edgeType":"calls","source":2764,"target":1574},{"edgeType":"calls","source":2318,"target":1394},{"edgeType":"calls","source":2892,"target":2891},{"edgeType":"contains","source":1113,"target":1813},{"edgeType":"calls","source":449,"target":669},{"edgeType":"contains","source":137,"target":887},{"edgeType":"contains","source":2767,"target":984},{"edgeType":"contains","source":2174,"target":2190},{"edgeType":"calls","source":134,"target":948},{"edgeType":"contains","source":352,"target":2120},{"edgeType":"contains","source":306,"target":375},{"edgeType":"calls","source":2818,"target":2836},{"edgeType":"calls","source":1652,"target":664},{"edgeType":"contains","source":298,"target":1680},{"edgeType":"imports","source":1836,"target":1844},{"edgeType":"contains","source":176,"target":177},{"edgeType":"contains","source":1472,"target":1490},{"edgeType":"contains","source":283,"target":823},{"edgeType":"contains","source":1234,"target":2526},{"edgeType":"calls","source":1352,"target":186},{"edgeType":"contains","source":513,"target":564},{"edgeType":"imports","source":457,"target":461},{"edgeType":"contains","source":1745,"target":1748},{"edgeType":"calls","source":479,"target":1088},{"edgeType":"contains","source":119,"target":2472},{"edgeType":"contains","source":125,"target":172},{"edgeType":"calls","source":1269,"target":1173},{"edgeType":"contains","source":1178,"target":1089},{"edgeType":"calls","source":1994,"target":2217},{"edgeType":"calls","source":2232,"target":2241},{"edgeType":"calls","source":236,"target":428},{"edgeType":"calls","source":2308,"target":1735},{"edgeType":"contains","source":1234,"target":2527},{"edgeType":"calls","source":1788,"target":675},{"edgeType":"calls","source":1802,"target":241},{"edgeType":"calls","source":1038,"target":670},{"edgeType":"calls","source":2172,"target":666},{"edgeType":"contains","source":1794,"target":2608},{"edgeType":"contains","source":25,"target":100},{"edgeType":"calls","source":977,"target":976},{"edgeType":"contains","source":430,"target":2079},{"edgeType":"calls","source":1079,"target":1249},{"edgeType":"calls","source":479,"target":1087},{"edgeType":"calls","source":2818,"target":195},{"edgeType":"contains","source":1167,"target":1169},{"edgeType":"contains","source":293,"target":1837},{"edgeType":"imports","source":1447,"target":1745},{"edgeType":"calls","source":1596,"target":288},{"edgeType":"calls","source":2010,"target":667},{"edgeType":"contains","source":306,"target":377},{"edgeType":"contains","source":2767,"target":982},{"edgeType":"calls","source":721,"target":194},{"edgeType":"calls","source":1788,"target":678},{"edgeType":"calls","source":2588,"target":187},{"edgeType":"contains","source":1111,"target":1319},{"edgeType":"calls","source":1899,"target":1201},{"edgeType":"contains","source":283,"target":825},{"edgeType":"contains","source":1794,"target":2341},{"edgeType":"contains","source":1234,"target":2524},{"edgeType":"calls","source":2679,"target":2651},{"edgeType":"calls","source":2196,"target":976},{"edgeType":"contains","source":25,"target":103},{"edgeType":"contains","source":513,"target":566},{"edgeType":"imports","source":457,"target":459},{"edgeType":"contains","source":125,"target":173},{"edgeType":"contains","source":1167,"target":1168},{"edgeType":"contains","source":305,"target":671},{"edgeType":"contains","source":87,"target":1615},{"edgeType":"contains","source":308,"target":314},{"edgeType":"calls","source":1899,"target":1200},{"edgeType":"calls","source":2818,"target":2835},{"edgeType":"calls","source":442,"target":122},{"edgeType":"contains","source":1234,"target":2525},{"edgeType":"calls","source":1352,"target":187},{"edgeType":"contains","source":17,"target":86},{"edgeType":"calls","source":1952,"target":878},{"edgeType":"contains","source":1794,"target":2606},{"edgeType":"contains","source":305,"target":935},{"edgeType":"calls","source":479,"target":1089},{"edgeType":"contains","source":11,"target":1593},{"edgeType":"contains","source":1031,"target":1159},{"edgeType":"contains","source":306,"target":379},{"edgeType":"calls","source":2025,"target":196},{"edgeType":"contains","source":308,"target":317},{"edgeType":"contains","source":293,"target":1839},{"edgeType":"contains","source":1794,"target":2611},{"edgeType":"calls","source":2615,"target":669},{"edgeType":"calls","source":1011,"target":976},{"edgeType":"calls","source":2172,"target":1189},{"edgeType":"contains","source":1234,"target":2530},{"edgeType":"calls","source":479,"target":1084},{"edgeType":"calls","source":2084,"target":1539},{"edgeType":"calls","source":1525,"target":1161},{"edgeType":"calls","source":2077,"target":1226},{"edgeType":"calls","source":1771,"target":670},{"edgeType":"calls","source":1899,"target":666},{"edgeType":"contains","source":1545,"target":1610},{"edgeType":"contains","source":57,"target":963},{"edgeType":"calls","source":1635,"target":1715},{"edgeType":"contains","source":513,"target":568},{"edgeType":"calls","source":2572,"target":681},{"edgeType":"imports","source":135,"target":134},{"edgeType":"calls","source":1400,"target":1336},{"edgeType":"calls","source":1312,"target":1950},{"edgeType":"contains","source":1,"target":55},{"edgeType":"calls","source":2025,"target":195},{"edgeType":"calls","source":2663,"target":2617},{"edgeType":"contains","source":283,"target":827},{"edgeType":"contains","source":1234,"target":2531},{"edgeType":"contains","source":6,"target":1221},{"edgeType":"calls","source":2429,"target":2472},{"edgeType":"contains","source":77,"target":78},{"edgeType":"calls","source":2588,"target":186},{"edgeType":"calls","source":479,"target":1083},{"edgeType":"calls","source":2077,"target":1225},{"edgeType":"contains","source":57,"target":962},{"edgeType":"contains","source":307,"target":1668},{"edgeType":"imports","source":457,"target":458},{"edgeType":"calls","source":1706,"target":570},{"edgeType":"contains","source":137,"target":863},{"edgeType":"contains","source":306,"target":381},{"edgeType":"calls","source":1033,"target":296},{"edgeType":"contains","source":1222,"target":2107},{"edgeType":"contains","source":1,"target":58},{"edgeType":"contains","source":2637,"target":2638},{"edgeType":"contains","source":67,"target":1183},{"edgeType":"contains","source":283,"target":830},{"edgeType":"contains","source":11,"target":13},{"edgeType":"calls","source":1352,"target":184},{"edgeType":"contains","source":1234,"target":2528},{"edgeType":"contains","source":513,"target":570},{"edgeType":"calls","source":1706,"target":573},{"edgeType":"calls","source":2077,"target":1228},{"edgeType":"contains","source":513,"target":306},{"edgeType":"contains","source":305,"target":676},{"edgeType":"calls","source":479,"target":1086},{"edgeType":"calls","source":2614,"target":2548},{"edgeType":"contains","source":1794,"target":1817},{"edgeType":"contains","source":1411,"target":1534},{"edgeType":"contains","source":1794,"target":2610},{"edgeType":"calls","source":1032,"target":326},{"edgeType":"contains","source":2637,"target":2639},{"edgeType":"calls","source":1173,"target":976},{"edgeType":"calls","source":1311,"target":662},{"edgeType":"calls","source":1686,"target":664},{"edgeType":"contains","source":283,"target":829},{"edgeType":"contains","source":1234,"target":2529},{"edgeType":"calls","source":134,"target":681},{"edgeType":"contains","source":11,"target":12},{"edgeType":"calls","source":1525,"target":1162},{"edgeType":"contains","source":298,"target":1156},{"edgeType":"calls","source":2077,"target":1227},{"edgeType":"contains","source":176,"target":1767},{"edgeType":"calls","source":1706,"target":572},{"edgeType":"calls","source":2448,"target":296},{"edgeType":"calls","source":479,"target":1085},{"edgeType":"calls","source":2588,"target":184},{"edgeType":"calls","source":2072,"target":589},{"edgeType":"contains","source":306,"target":383},{"edgeType":"calls","source":141,"target":194},{"edgeType":"calls","source":2008,"target":1776},{"edgeType":"calls","source":1079,"target":1242},{"edgeType":"contains","source":283,"target":832},{"edgeType":"contains","source":137,"target":865},{"edgeType":"contains","source":1,"target":60},{"edgeType":"calls","source":2672,"target":2597},{"edgeType":"contains","source":1234,"target":2534},{"edgeType":"imports","source":1234,"target":430},{"edgeType":"contains","source":2637,"target":2644},{"edgeType":"contains","source":513,"target":572},{"edgeType":"imports","source":1836,"target":1853},{"edgeType":"contains","source":1985,"target":2244},{"edgeType":"calls","source":2818,"target":186},{"edgeType":"contains","source":19,"target":31},{"edgeType":"contains","source":1545,"target":1614},{"edgeType":"contains","source":87,"target":1094},{"edgeType":"calls","source":2818,"target":2829},{"edgeType":"contains","source":969,"target":970},{"edgeType":"contains","source":2075,"target":2097},{"edgeType":"contains","source":1234,"target":2535},{"edgeType":"imports","source":1234,"target":1488},{"edgeType":"contains","source":11,"target":14},{"edgeType":"calls","source":2085,"target":973},{"edgeType":"calls","source":2818,"target":187},{"edgeType":"imports","source":1447,"target":1755},{"edgeType":"calls","source":2452,"target":170},{"edgeType":"calls","source":134,"target":675},{"edgeType":"contains","source":66,"target":687},{"edgeType":"calls","source":2572,"target":678},{"edgeType":"calls","source":1942,"target":1706},{"edgeType":"calls","source":1961,"target":1117},{"edgeType":"contains","source":306,"target":385},{"edgeType":"contains","source":308,"target":323},{"edgeType":"calls","source":2752,"target":2758},{"edgeType":"calls","source":2818,"target":2826},{"edgeType":"contains","source":283,"target":834},{"edgeType":"contains","source":1439,"target":1462},{"edgeType":"contains","source":1234,"target":2532},{"edgeType":"calls","source":2818,"target":976},{"edgeType":"calls","source":479,"target":1082},{"edgeType":"calls","source":2639,"target":976},{"edgeType":"calls","source":2818,"target":184},{"edgeType":"calls","source":1360,"target":196},{"edgeType":"calls","source":134,"target":678},{"edgeType":"contains","source":980,"target":2217},{"edgeType":"calls","source":2572,"target":675},{"edgeType":"contains","source":1545,"target":1612},{"edgeType":"contains","source":19,"target":33},{"edgeType":"calls","source":1870,"target":1827},{"edgeType":"calls","source":2818,"target":2827},{"edgeType":"contains","source":137,"target":866},{"edgeType":"contains","source":1854,"target":2075},{"edgeType":"contains","source":1234,"target":2533},{"edgeType":"contains","source":2637,"target":2643},{"edgeType":"contains","source":126,"target":1472},{"edgeType":"calls","source":2896,"target":2787},{"edgeType":"contains","source":1472,"target":2026},{"edgeType":"contains","source":513,"target":573},{"edgeType":"calls","source":1360,"target":195},{"edgeType":"contains","source":1794,"target":2350},{"edgeType":"contains","source":1545,"target":1613},{"edgeType":"contains","source":1,"target":1650},{"edgeType":"contains","source":19,"target":35},{"edgeType":"calls","source":2818,"target":2824},{"edgeType":"imports","source":1447,"target":430},{"edgeType":"calls","source":2038,"target":1106},{"edgeType":"calls","source":2494,"target":976},{"edgeType":"contains","source":177,"target":951},{"edgeType":"contains","source":513,"target":577},{"edgeType":"contains","source":2563,"target":2564},{"edgeType":"contains","source":87,"target":305},{"edgeType":"contains","source":126,"target":153},{"edgeType":"calls","source":1952,"target":1922},{"edgeType":"contains","source":1,"target":65},{"edgeType":"calls","source":2337,"target":2144},{"edgeType":"contains","source":1545,"target":1618},{"edgeType":"contains","source":1985,"target":2248},{"edgeType":"calls","source":1992,"target":2003},{"edgeType":"calls","source":2429,"target":2463},{"edgeType":"contains","source":1222,"target":2382},{"edgeType":"calls","source":1942,"target":1703},{"edgeType":"contains","source":1447,"target":2542},{"edgeType":"contains","source":306,"target":387},{"edgeType":"calls","source":2354,"target":296},{"edgeType":"calls","source":2025,"target":187},{"edgeType":"imports","source":457,"target":201},{"edgeType":"contains","source":980,"target":1426},{"edgeType":"calls","source":2541,"target":1898},{"edgeType":"calls","source":1631,"target":1038},{"edgeType":"contains","source":175,"target":219},{"edgeType":"calls","source":2818,"target":2825},{"edgeType":"calls","source":2008,"target":2035},{"edgeType":"contains","source":137,"target":868},{"edgeType":"contains","source":1,"target":63},{"edgeType":"calls","source":1244,"target":878},{"edgeType":"contains","source":1545,"target":1619},{"edgeType":"calls","source":2615,"target":662},{"edgeType":"calls","source":995,"target":670},{"edgeType":"contains","source":430,"target":2091},{"edgeType":"contains","source":1762,"target":1763},{"edgeType":"calls","source":2025,"target":186},{"edgeType":"calls","source":2752,"target":2757},{"edgeType":"calls","source":1942,"target":1702},{"edgeType":"contains","source":293,"target":1846},{"edgeType":"calls","source":1633,"target":2032},{"edgeType":"calls","source":2008,"target":1774},{"edgeType":"calls","source":2383,"target":451},{"edgeType":"contains","source":1721,"target":1973},{"edgeType":"calls","source":2764,"target":1589},{"edgeType":"contains","source":135,"target":2255},{"edgeType":"contains","source":25,"target":115},{"edgeType":"contains","source":11,"target":1606},{"edgeType":"calls","source":1788,"target":666},{"edgeType":"contains","source":87,"target":307},{"edgeType":"contains","source":1,"target":67},{"edgeType":"contains","source":3,"target":5},{"edgeType":"imports","source":1447,"target":164},{"edgeType":"calls","source":1251,"target":664},{"edgeType":"calls","source":1771,"target":664},{"edgeType":"calls","source":2818,"target":2822},{"edgeType":"calls","source":1942,"target":1705},{"edgeType":"contains","source":1545,"target":1616},{"edgeType":"contains","source":306,"target":389},{"edgeType":"contains","source":1868,"target":1909},{"edgeType":"contains","source":1060,"target":1062},{"edgeType":"contains","source":19,"target":36},{"edgeType":"calls","source":1760,"target":476},{"edgeType":"calls","source":1430,"target":664},{"edgeType":"contains","source":1794,"target":2354},{"edgeType":"contains","source":1234,"target":2537},{"edgeType":"calls","source":1319,"target":670},{"edgeType":"contains","source":513,"target":578},{"edgeType":"calls","source":256,"target":326},{"edgeType":"imports","source":980,"target":107},{"edgeType":"contains","source":137,"target":870},{"edgeType":"contains","source":1297,"target":2434},{"edgeType":"calls","source":2085,"target":971},{"edgeType":"contains","source":119,"target":2485},{"edgeType":"contains","source":1545,"target":1617},{"edgeType":"calls","source":2818,"target":2823}],"nodes":[{"groupName":"","id":1,"nodeType":"Repo","repoName":"pallets#flask#182ce3dd15dfa3537391c3efaf9c3ff407d134d4"},{"id":2,"name":"examples/tutorial/flaskr/static","nodeType":"Package"},{"id":3,"name":"tests/typing","nodeType":"Package"},{"id":4,"name":"style.css","nodeType":"TextFile","path":"examples/tutorial/flaskr/static","text":"html {\n font-family: sans-serif;\n background: #eee;\n padding: 1rem;\n}\n\nbody {\n max-width: 960px;\n margin: 0 auto;\n background: white;\n}\n\nh1, h2, h3, h4, h5, h6 {\n font-family: serif;\n color: #377ba8;\n margin: 1rem 0;\n}\n\na {\n color: #377ba8;\n}\n\nhr {\n border: none;\n border-top: 1px solid lightgray;\n}\n\nnav {\n background: lightgray;\n display: flex;\n align-items: center;\n padding: 0 0.5rem;\n}\n\nnav h1 {\n flex: auto;\n margin: 0;\n}\n\nnav h1 a {\n text-decoration: none;\n padding: 0.25rem 0.5rem;\n}\n\nnav ul {\n display: flex;\n list-style: none;\n margin: 0;\n padding: 0;\n}\n\nnav ul li a, nav ul li span, header .action {\n display: block;\n padding: 0.5rem;\n}\n\n.content {\n padding: 0 1rem 1rem;\n}\n\n.content > header {\n border-bottom: 1px solid lightgray;\n display: flex;\n align-items: flex-end;\n}\n\n.content > header h1 {\n flex: auto;\n margin: 1rem 0 0.25rem 0;\n}\n\n.flash {\n margin: 1em 0;\n padding: 1em;\n background: #cae6f6;\n border: 1px solid #377ba8;\n}\n\n.post > header {\n display: flex;\n align-items: flex-end;\n font-size: 0.85em;\n}\n\n.post > header > div:first-of-type {\n flex: auto;\n}\n\n.post > header h1 {\n font-size: 1.5em;\n margin-bottom: 0;\n}\n\n.post .about {\n color: slategray;\n font-style: italic;\n}\n\n.post .body {\n white-space: pre-line;\n}\n\n.content:last-child {\n margin-bottom: 0;\n}\n\n.content form {\n margin: 1em 0;\n display: flex;\n flex-direction: column;\n}\n\n.content label {\n font-weight: bold;\n margin-bottom: 0.5em;\n}\n\n.content input, .content textarea {\n margin-bottom: 1em;\n}\n\n.content textarea {\n min-height: 12em;\n resize: vertical;\n}\n\ninput.danger {\n color: #cc2f2e;\n}\n\ninput[type=submit] {\n align-self: start;\n min-width: 10em;\n}\n"},{"fileName":"typing_app_decorators.py","filePath":"tests/typing","id":5,"nodeType":"File","text":"from __future__ import annotations\n\nimport typing as t\n\nfrom flask import Flask\nfrom flask import Response\n\napp = Flask(__name__)\n\n\n@app.after_request\ndef after_sync(response: Response) -> Response:\n return Response()\n\n\n@app.after_request\nasync def after_async(response: Response) -> Response:\n return Response()\n\n\n@app.before_request\ndef before_sync() -> None:\n ...\n\n\n@app.before_request\nasync def before_async() -> None:\n ...\n\n\n@app.teardown_appcontext\ndef teardown_sync(exc: t.Optional[BaseException]) -> None:\n ...\n\n\n@app.teardown_appcontext\nasync def teardown_async(exc: t.Optional[BaseException]) -> None:\n ...\n"},{"id":6,"name":"","nodeType":"Package"},{"id":7,"name":".gitignore","nodeType":"TextFile","path":"","text":".DS_Store\n.env\n.flaskenv\n*.pyc\n*.pyo\nenv/\nvenv/\n.venv/\nenv*\ndist/\nbuild/\n*.egg\n*.egg-info/\n.tox/\n.cache/\n.pytest_cache/\n.idea/\ndocs/_build/\n.vscode\n\n# Coverage reports\nhtmlcov/\n.coverage\n.coverage.*\n*,cover\n"},{"id":8,"name":"requirements","nodeType":"Package"},{"id":9,"name":"docs.in","nodeType":"TextFile","path":"requirements","text":"Pallets-Sphinx-Themes\n# sphinx 5 introduced error in references from werkzeug in docstrings\nSphinx < 5\nsphinx-issues\nsphinxcontrib-log-cabinet\n# sphinx-tabs 3.4 requires docutils 0.18, sphinx < 5 requires < 0.18\nsphinx-tabs < 3.4\n"},{"id":10,"name":"docs.txt","nodeType":"TextFile","path":"requirements","text":"# SHA1:323f1c1134d78952ea63131c187303def63b56bd\n#\n# This file is autogenerated by pip-compile-multi\n# To update, run:\n#\n# pip-compile-multi\n#\nalabaster==0.7.13\n # via sphinx\nbabel==2.12.1\n # via sphinx\ncertifi==2022.12.7\n # via requests\ncharset-normalizer==3.1.0\n # via requests\ndocutils==0.17.1\n # via\n # sphinx\n # sphinx-tabs\nidna==3.4\n # via requests\nimagesize==1.4.1\n # via sphinx\njinja2==3.1.2\n # via sphinx\nmarkupsafe==2.1.2\n # via jinja2\npackaging==23.0\n # via\n # pallets-sphinx-themes\n # sphinx\npallets-sphinx-themes==2.0.3\n # via -r requirements/docs.in\npygments==2.15.0\n # via\n # sphinx\n # sphinx-tabs\nrequests==2.28.2\n # via sphinx\nsnowballstemmer==2.2.0\n # via sphinx\nsphinx==4.5.0\n # via\n # -r requirements/docs.in\n # pallets-sphinx-themes\n # sphinx-issues\n # sphinx-tabs\n # sphinxcontrib-log-cabinet\nsphinx-issues==3.0.1\n # via -r requirements/docs.in\nsphinx-tabs==3.3.1\n # via -r requirements/docs.in\nsphinxcontrib-applehelp==1.0.4\n # via sphinx\nsphinxcontrib-devhelp==1.0.2\n # via sphinx\nsphinxcontrib-htmlhelp==2.0.1\n # via sphinx\nsphinxcontrib-jsmath==1.0.1\n # via sphinx\nsphinxcontrib-log-cabinet==1.0.1\n # via -r requirements/docs.in\nsphinxcontrib-qthelp==1.0.3\n # via sphinx\nsphinxcontrib-serializinghtml==1.1.5\n # via sphinx\nurllib3==1.26.15\n # via requests\n"},{"id":11,"name":"docs/patterns","nodeType":"Package"},{"id":12,"name":"singlepageapplications.rst","nodeType":"TextFile","path":"docs/patterns","text":"Single-Page Applications\n========================\n\nFlask can be used to serve Single-Page Applications (SPA) by placing static\nfiles produced by your frontend framework in a subfolder inside of your\nproject. You will also need to create a catch-all endpoint that routes all\nrequests to your SPA.\n\nThe following example demonstrates how to serve an SPA along with an API::\n\n from flask import Flask, jsonify\n\n app = Flask(__name__, static_folder='app', static_url_path=\"/app\")\n\n\n @app.route(\"/heartbeat\")\n def heartbeat():\n return jsonify({\"status\": \"healthy\"})\n\n\n @app.route('/', defaults={'path': ''})\n @app.route('/')\n def catch_all(path):\n return app.send_static_file(\"index.html\")\n"},{"id":13,"name":"subclassing.rst","nodeType":"TextFile","path":"docs/patterns","text":"Subclassing Flask\n=================\n\nThe :class:`~flask.Flask` class is designed for subclassing.\n\nFor example, you may want to override how request parameters are handled to preserve their order::\n\n from flask import Flask, Request\n from werkzeug.datastructures import ImmutableOrderedMultiDict\n class MyRequest(Request):\n \"\"\"Request subclass to override request parameter storage\"\"\"\n parameter_storage_class = ImmutableOrderedMultiDict\n class MyFlask(Flask):\n \"\"\"Flask subclass using the custom request class\"\"\"\n request_class = MyRequest\n\nThis is the recommended approach for overriding or augmenting Flask's internal functionality.\n"},{"id":14,"name":"jquery.rst","nodeType":"TextFile","path":"docs/patterns","text":":orphan:\n\nAJAX with jQuery\n================\n\nObsolete, see :doc:`/patterns/javascript` instead.\n"},{"id":15,"name":"tests/static","nodeType":"Package"},{"id":16,"name":"config.toml","nodeType":"TextFile","path":"tests/static","text":"TEST_KEY=\"foo\"\nSECRET_KEY=\"config\"\n"},{"id":17,"name":"artwork","nodeType":"Package"},{"id":18,"name":"LICENSE.rst","nodeType":"TextFile","path":"artwork","text":"Copyright 2010 Pallets\n\nThis logo or a modified version may be used by anyone to refer to the\nFlask project, but does not indicate endorsement by the project.\n\nRedistribution and use in source (SVG) and binary (renders in PNG, etc.)\nforms, with or without modification, are permitted provided that the\nfollowing conditions are met:\n\n1. Redistributions of source code must retain the above copyright\n notice and this list of conditions.\n\n2. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nWe would appreciate that you make the image a link to\nhttps://palletsprojects.com/p/flask/ if you use it in a medium that\nsupports links.\n"},{"id":19,"name":"docs/deploying","nodeType":"Package"},{"id":20,"name":"index.rst","nodeType":"TextFile","path":"docs/deploying","text":"Deploying to Production\n=======================\n\nAfter developing your application, you'll want to make it available\npublicly to other users. When you're developing locally, you're probably\nusing the built-in development server, debugger, and reloader. These\nshould not be used in production. Instead, you should use a dedicated\nWSGI server or hosting platform, some of which will be described here.\n\n\"Production\" means \"not development\", which applies whether you're\nserving your application publicly to millions of users or privately /\nlocally to a single user. **Do not use the development server when\ndeploying to production. It is intended for use only during local\ndevelopment. It is not designed to be particularly secure, stable, or\nefficient.**\n\nSelf-Hosted Options\n-------------------\n\nFlask is a WSGI *application*. A WSGI *server* is used to run the\napplication, converting incoming HTTP requests to the standard WSGI\nenviron, and converting outgoing WSGI responses to HTTP responses.\n\nThe primary goal of these docs is to familiarize you with the concepts\ninvolved in running a WSGI application using a production WSGI server\nand HTTP server. There are many WSGI servers and HTTP servers, with many\nconfiguration possibilities. The pages below discuss the most common\nservers, and show the basics of running each one. The next section\ndiscusses platforms that can manage this for you.\n\n.. toctree::\n :maxdepth: 1\n\n gunicorn\n waitress\n mod_wsgi\n uwsgi\n gevent\n eventlet\n asgi\n\nWSGI servers have HTTP servers built-in. However, a dedicated HTTP\nserver may be safer, more efficient, or more capable. Putting an HTTP\nserver in front of the WSGI server is called a \"reverse proxy.\"\n\n.. toctree::\n :maxdepth: 1\n\n proxy_fix\n nginx\n apache-httpd\n\nThis list is not exhaustive, and you should evaluate these and other\nservers based on your application's needs. Different servers will have\ndifferent capabilities, configuration, and support.\n\n\nHosting Platforms\n-----------------\n\nThere are many services available for hosting web applications without\nneeding to maintain your own server, networking, domain, etc. Some\nservices may have a free tier up to a certain time or bandwidth. Many of\nthese services use one of the WSGI servers described above, or a similar\ninterface. The links below are for some of the most common platforms,\nwhich have instructions for Flask, WSGI, or Python.\n\n- `PythonAnywhere `_\n- `Google App Engine `_\n- `Google Cloud Run `_\n- `AWS Elastic Beanstalk `_\n- `Microsoft Azure `_\n\nThis list is not exhaustive, and you should evaluate these and other\nservices based on your application's needs. Different services will have\ndifferent capabilities, configuration, pricing, and support.\n\nYou'll probably need to :doc:`proxy_fix` when using most hosting\nplatforms.\n"},{"id":21,"name":"nginx.rst","nodeType":"TextFile","path":"docs/deploying","text":"nginx\n=====\n\n`nginx`_ is a fast, production level HTTP server. When serving your\napplication with one of the WSGI servers listed in :doc:`index`, it is\noften good or necessary to put a dedicated HTTP server in front of it.\nThis \"reverse proxy\" can handle incoming requests, TLS, and other\nsecurity and performance concerns better than the WSGI server.\n\nNginx can be installed using your system package manager, or a pre-built\nexecutable for Windows. Installing and running Nginx itself is outside\nthe scope of this doc. This page outlines the basics of configuring\nNginx to proxy your application. Be sure to read its documentation to\nunderstand what features are available.\n\n.. _nginx: https://nginx.org/\n\n\nDomain Name\n-----------\n\nAcquiring and configuring a domain name is outside the scope of this\ndoc. In general, you will buy a domain name from a registrar, pay for\nserver space with a hosting provider, and then point your registrar\nat the hosting provider's name servers.\n\nTo simulate this, you can also edit your ``hosts`` file, located at\n``/etc/hosts`` on Linux. Add a line that associates a name with the\nlocal IP.\n\nModern Linux systems may be configured to treat any domain name that\nends with ``.localhost`` like this without adding it to the ``hosts``\nfile.\n\n.. code-block:: python\n :caption: ``/etc/hosts``\n\n 127.0.0.1 hello.localhost\n\n\nConfiguration\n-------------\n\nThe nginx configuration is located at ``/etc/nginx/nginx.conf`` on\nLinux. It may be different depending on your operating system. Check the\ndocs and look for ``nginx.conf``.\n\nRemove or comment out any existing ``server`` section. Add a ``server``\nsection and use the ``proxy_pass`` directive to point to the address the\nWSGI server is listening on. We'll assume the WSGI server is listening\nlocally at ``http://127.0.0.1:8000``.\n\n.. code-block:: nginx\n :caption: ``/etc/nginx.conf``\n\n server {\n listen 80;\n server_name _;\n\n location / {\n proxy_pass http://127.0.0.1:8000/;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_set_header X-Forwarded-Host $host;\n proxy_set_header X-Forwarded-Prefix /;\n }\n }\n\nThen :doc:`proxy_fix` so that your application uses these headers.\n"},{"id":22,"name":"appfactories.rst","nodeType":"TextFile","path":"docs/patterns","text":"Application Factories\n=====================\n\nIf you are already using packages and blueprints for your application\n(:doc:`/blueprints`) there are a couple of really nice ways to further improve\nthe experience. A common pattern is creating the application object when\nthe blueprint is imported. But if you move the creation of this object\ninto a function, you can then create multiple instances of this app later.\n\nSo why would you want to do this?\n\n1. Testing. You can have instances of the application with different\n settings to test every case.\n2. Multiple instances. Imagine you want to run different versions of the\n same application. Of course you could have multiple instances with\n different configs set up in your webserver, but if you use factories,\n you can have multiple instances of the same application running in the\n same application process which can be handy.\n\nSo how would you then actually implement that?\n\nBasic Factories\n---------------\n\nThe idea is to set up the application in a function. Like this::\n\n def create_app(config_filename):\n app = Flask(__name__)\n app.config.from_pyfile(config_filename)\n\n from yourapplication.model import db\n db.init_app(app)\n\n from yourapplication.views.admin import admin\n from yourapplication.views.frontend import frontend\n app.register_blueprint(admin)\n app.register_blueprint(frontend)\n\n return app\n\nThe downside is that you cannot use the application object in the blueprints\nat import time. You can however use it from within a request. How do you\nget access to the application with the config? Use\n:data:`~flask.current_app`::\n\n from flask import current_app, Blueprint, render_template\n admin = Blueprint('admin', __name__, url_prefix='/admin')\n\n @admin.route('/')\n def index():\n return render_template(current_app.config['INDEX_TEMPLATE'])\n\nHere we look up the name of a template in the config.\n\nFactories & Extensions\n----------------------\n\nIt's preferable to create your extensions and app factories so that the\nextension object does not initially get bound to the application.\n\nUsing `Flask-SQLAlchemy `_,\nas an example, you should not do something along those lines::\n\n def create_app(config_filename):\n app = Flask(__name__)\n app.config.from_pyfile(config_filename)\n\n db = SQLAlchemy(app)\n\nBut, rather, in model.py (or equivalent)::\n\n db = SQLAlchemy()\n\nand in your application.py (or equivalent)::\n\n def create_app(config_filename):\n app = Flask(__name__)\n app.config.from_pyfile(config_filename)\n\n from yourapplication.model import db\n db.init_app(app)\n\nUsing this design pattern, no application-specific state is stored on the\nextension object, so one extension object can be used for multiple apps.\nFor more information about the design of extensions refer to :doc:`/extensiondev`.\n\nUsing Applications\n------------------\n\nTo run such an application, you can use the :command:`flask` command:\n\n.. code-block:: text\n\n $ flask --app hello run\n\nFlask will automatically detect the factory if it is named\n``create_app`` or ``make_app`` in ``hello``. You can also pass arguments\nto the factory like this:\n\n.. code-block:: text\n\n $ flask --app hello:create_app(local_auth=True) run\n\nThen the ``create_app`` factory in ``myapp`` is called with the keyword\nargument ``local_auth=True``. See :doc:`/cli` for more detail.\n\nFactory Improvements\n--------------------\n\nThe factory function above is not very clever, but you can improve it.\nThe following changes are straightforward to implement:\n\n1. Make it possible to pass in configuration values for unit tests so that\n you don't have to create config files on the filesystem.\n2. Call a function from a blueprint when the application is setting up so\n that you have a place to modify attributes of the application (like\n hooking in before/after request handlers etc.)\n3. Add in WSGI middlewares when the application is being created if necessary.\n"},{"id":23,"name":"build.in","nodeType":"TextFile","path":"requirements","text":"build\n"},{"id":24,"name":"flashing.rst","nodeType":"TextFile","path":"docs/patterns","text":"Message Flashing\n================\n\nGood applications and user interfaces are all about feedback. If the user\ndoes not get enough feedback they will probably end up hating the\napplication. Flask provides a really simple way to give feedback to a\nuser with the flashing system. The flashing system basically makes it\npossible to record a message at the end of a request and access it next\nrequest and only next request. This is usually combined with a layout\ntemplate that does this. Note that browsers and sometimes web servers enforce\na limit on cookie sizes. This means that flashing messages that are too\nlarge for session cookies causes message flashing to fail silently.\n\nSimple Flashing\n---------------\n\nSo here is a full example::\n\n from flask import Flask, flash, redirect, render_template, \\\n request, url_for\n\n app = Flask(__name__)\n app.secret_key = b'_5#y2L\"F4Q8z\\n\\xec]/'\n\n @app.route('/')\n def index():\n return render_template('index.html')\n\n @app.route('/login', methods=['GET', 'POST'])\n def login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != 'admin' or \\\n request.form['password'] != 'secret':\n error = 'Invalid credentials'\n else:\n flash('You were successfully logged in')\n return redirect(url_for('index'))\n return render_template('login.html', error=error)\n\nAnd here is the :file:`layout.html` template which does the magic:\n\n.. sourcecode:: html+jinja\n\n \n My Application\n {% with messages = get_flashed_messages() %}\n {% if messages %}\n
    \n {% for message in messages %}\n
  • {{ message }}
  • \n {% endfor %}\n
\n {% endif %}\n {% endwith %}\n {% block body %}{% endblock %}\n\nHere is the :file:`index.html` template which inherits from :file:`layout.html`:\n\n.. sourcecode:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block body %}\n

Overview

\n

Do you want to log in?\n {% endblock %}\n\nAnd here is the :file:`login.html` template which also inherits from\n:file:`layout.html`:\n\n.. sourcecode:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block body %}\n

Login

\n {% if error %}\n

Error: {{ error }}\n {% endif %}\n

\n
\n
Username:\n
\n
Password:\n
\n
\n

\n

\n {% endblock %}\n\nFlashing With Categories\n------------------------\n\n.. versionadded:: 0.3\n\nIt is also possible to provide categories when flashing a message. The\ndefault category if nothing is provided is ``'message'``. Alternative\ncategories can be used to give the user better feedback. For example\nerror messages could be displayed with a red background.\n\nTo flash a message with a different category, just use the second argument\nto the :func:`~flask.flash` function::\n\n flash('Invalid password provided', 'error')\n\nInside the template you then have to tell the\n:func:`~flask.get_flashed_messages` function to also return the\ncategories. The loop looks slightly different in that situation then:\n\n.. sourcecode:: html+jinja\n\n {% with messages = get_flashed_messages(with_categories=true) %}\n {% if messages %}\n
    \n {% for category, message in messages %}\n
  • {{ message }}
  • \n {% endfor %}\n
\n {% endif %}\n {% endwith %}\n\nThis is just one example of how to render these flashed messages. One\nmight also use the category to add a prefix such as\n``Error:`` to the message.\n\nFiltering Flash Messages\n------------------------\n\n.. versionadded:: 0.9\n\nOptionally you can pass a list of categories which filters the results of\n:func:`~flask.get_flashed_messages`. This is useful if you wish to\nrender each category in a separate block.\n\n.. sourcecode:: html+jinja\n\n {% with errors = get_flashed_messages(category_filter=[\"error\"]) %}\n {% if errors %}\n
\n ×\n
    \n {%- for msg in errors %}\n
  • {{ msg }}
  • \n {% endfor -%}\n
\n
\n {% endif %}\n {% endwith %}\n"},{"id":25,"name":"docs","nodeType":"Package"},{"id":26,"name":"async-await.rst","nodeType":"TextFile","path":"docs","text":".. _async_await:\n\nUsing ``async`` and ``await``\n=============================\n\n.. versionadded:: 2.0\n\nRoutes, error handlers, before request, after request, and teardown\nfunctions can all be coroutine functions if Flask is installed with the\n``async`` extra (``pip install flask[async]``). This allows views to be\ndefined with ``async def`` and use ``await``.\n\n.. code-block:: python\n\n @app.route(\"/get-data\")\n async def get_data():\n data = await async_db_query(...)\n return jsonify(data)\n\nPluggable class-based views also support handlers that are implemented as\ncoroutines. This applies to the :meth:`~flask.views.View.dispatch_request`\nmethod in views that inherit from the :class:`flask.views.View` class, as\nwell as all the HTTP method handlers in views that inherit from the\n:class:`flask.views.MethodView` class.\n\n.. admonition:: Using ``async`` on Windows on Python 3.8\n\n Python 3.8 has a bug related to asyncio on Windows. If you encounter\n something like ``ValueError: set_wakeup_fd only works in main thread``,\n please upgrade to Python 3.9.\n\n.. admonition:: Using ``async`` with greenlet\n\n When using gevent or eventlet to serve an application or patch the\n runtime, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is\n required.\n\n\nPerformance\n-----------\n\nAsync functions require an event loop to run. Flask, as a WSGI\napplication, uses one worker to handle one request/response cycle.\nWhen a request comes in to an async view, Flask will start an event loop\nin a thread, run the view function there, then return the result.\n\nEach request still ties up one worker, even for async views. The upside\nis that you can run async code within a view, for example to make\nmultiple concurrent database queries, HTTP requests to an external API,\netc. However, the number of requests your application can handle at one\ntime will remain the same.\n\n**Async is not inherently faster than sync code.** Async is beneficial\nwhen performing concurrent IO-bound tasks, but will probably not improve\nCPU-bound tasks. Traditional Flask views will still be appropriate for\nmost use cases, but Flask's async support enables writing and using\ncode that wasn't possible natively before.\n\n\nBackground tasks\n----------------\n\nAsync functions will run in an event loop until they complete, at\nwhich stage the event loop will stop. This means any additional\nspawned tasks that haven't completed when the async function completes\nwill be cancelled. Therefore you cannot spawn background tasks, for\nexample via ``asyncio.create_task``.\n\nIf you wish to use background tasks it is best to use a task queue to\ntrigger background work, rather than spawn tasks in a view\nfunction. With that in mind you can spawn asyncio tasks by serving\nFlask with an ASGI server and utilising the asgiref WsgiToAsgi adapter\nas described in :doc:`deploying/asgi`. This works as the adapter creates\nan event loop that runs continually.\n\n\nWhen to use Quart instead\n-------------------------\n\nFlask's async support is less performant than async-first frameworks due\nto the way it is implemented. If you have a mainly async codebase it\nwould make sense to consider `Quart`_. Quart is a reimplementation of\nFlask based on the `ASGI`_ standard instead of WSGI. This allows it to\nhandle many concurrent requests, long running requests, and websockets\nwithout requiring multiple worker processes or threads.\n\nIt has also already been possible to run Flask with Gevent or Eventlet\nto get many of the benefits of async request handling. These libraries\npatch low-level Python functions to accomplish this, whereas ``async``/\n``await`` and ASGI use standard, modern Python capabilities. Deciding\nwhether you should use Flask, Quart, or something else is ultimately up\nto understanding the specific needs of your project.\n\n.. _Quart: https://github.com/pallets/quart\n.. _ASGI: https://asgi.readthedocs.io/en/latest/\n\n\nExtensions\n----------\n\nFlask extensions predating Flask's async support do not expect async views.\nIf they provide decorators to add functionality to views, those will probably\nnot work with async views because they will not await the function or be\nawaitable. Other functions they provide will not be awaitable either and\nwill probably be blocking if called within an async view.\n\nExtension authors can support async functions by utilising the\n:meth:`flask.Flask.ensure_sync` method. For example, if the extension\nprovides a view function decorator add ``ensure_sync`` before calling\nthe decorated function,\n\n.. code-block:: python\n\n def extension(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n ... # Extension logic\n return current_app.ensure_sync(func)(*args, **kwargs)\n\n return wrapper\n\nCheck the changelog of the extension you want to use to see if they've\nimplemented async support, or make a feature request or PR to them.\n\n\nOther event loops\n-----------------\n\nAt the moment Flask only supports :mod:`asyncio`. It's possible to\noverride :meth:`flask.Flask.ensure_sync` to change how async functions\nare wrapped to use a different library.\n"},{"id":27,"name":"server.rst","nodeType":"TextFile","path":"docs","text":".. currentmodule:: flask\n\nDevelopment Server\n==================\n\nFlask provides a ``run`` command to run the application with a development server. In\ndebug mode, this server provides an interactive debugger and will reload when code is\nchanged.\n\n.. warning::\n\n Do not use the development server when deploying to production. It\n is intended for use only during local development. It is not\n designed to be particularly efficient, stable, or secure.\n\n See :doc:`/deploying/index` for deployment options.\n\nCommand Line\n------------\n\nThe ``flask run`` CLI command is the recommended way to run the development server. Use\nthe ``--app`` option to point to your application, and the ``--debug`` option to enable\ndebug mode.\n\n.. code-block:: text\n\n $ flask --app hello run --debug\n\nThis enables debug mode, including the interactive debugger and reloader, and then\nstarts the server on http://localhost:5000/. Use ``flask run --help`` to see the\navailable options, and :doc:`/cli` for detailed instructions about configuring and using\nthe CLI.\n\n\n.. _address-already-in-use:\n\nAddress already in use\n~~~~~~~~~~~~~~~~~~~~~~\n\nIf another program is already using port 5000, you'll see an ``OSError``\nwhen the server tries to start. It may have one of the following\nmessages:\n\n- ``OSError: [Errno 98] Address already in use``\n- ``OSError: [WinError 10013] An attempt was made to access a socket\n in a way forbidden by its access permissions``\n\nEither identify and stop the other program, or use\n``flask run --port 5001`` to pick a different port.\n\nYou can use ``netstat`` or ``lsof`` to identify what process id is using\na port, then use other operating system tools stop that process. The\nfollowing example shows that process id 6847 is using port 5000.\n\n.. tabs::\n\n .. tab:: ``netstat`` (Linux)\n\n .. code-block:: text\n\n $ netstat -nlp | grep 5000\n tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 6847/python\n\n .. tab:: ``lsof`` (macOS / Linux)\n\n .. code-block:: text\n\n $ lsof -P -i :5000\n Python 6847 IPv4 TCP localhost:5000 (LISTEN)\n\n .. tab:: ``netstat`` (Windows)\n\n .. code-block:: text\n\n > netstat -ano | findstr 5000\n TCP 127.0.0.1:5000 0.0.0.0:0 LISTENING 6847\n\nmacOS Monterey and later automatically starts a service that uses port\n5000. To disable the service, go to System Preferences, Sharing, and\ndisable \"AirPlay Receiver\".\n\n\nDeferred Errors on Reload\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen using the ``flask run`` command with the reloader, the server will\ncontinue to run even if you introduce syntax errors or other\ninitialization errors into the code. Accessing the site will show the\ninteractive debugger for the error, rather than crashing the server.\n\nIf a syntax error is already present when calling ``flask run``, it will\nfail immediately and show the traceback rather than waiting until the\nsite is accessed. This is intended to make errors more visible initially\nwhile still allowing the server to handle errors on reload.\n\n\nIn Code\n-------\n\nThe development server can also be started from Python with the :meth:`Flask.run`\nmethod. This method takes arguments similar to the CLI options to control the server.\nThe main difference from the CLI command is that the server will crash if there are\nerrors when reloading. ``debug=True`` can be passed to enable debug mode.\n\nPlace the call in a main block, otherwise it will interfere when trying to import and\nrun the application with a production server later.\n\n.. code-block:: python\n\n if __name__ == \"__main__\":\n app.run(debug=True)\n\n.. code-block:: text\n\n $ python hello.py\n"},{"id":28,"name":"tests-pallets-min.in","nodeType":"TextFile","path":"requirements","text":"Werkzeug==2.0.0\nJinja2==3.0.0\nMarkupSafe==2.0.0\nitsdangerous==2.0.0\nclick==8.0.0\nblinker==1.6.2\n"},{"id":29,"name":"appcontext.rst","nodeType":"TextFile","path":"docs","text":".. currentmodule:: flask\n\nThe Application Context\n=======================\n\nThe application context keeps track of the application-level data during\na request, CLI command, or other activity. Rather than passing the\napplication around to each function, the :data:`current_app` and\n:data:`g` proxies are accessed instead.\n\nThis is similar to :doc:`/reqcontext`, which keeps track of\nrequest-level data during a request. A corresponding application context\nis pushed when a request context is pushed.\n\nPurpose of the Context\n----------------------\n\nThe :class:`Flask` application object has attributes, such as\n:attr:`~Flask.config`, that are useful to access within views and\n:doc:`CLI commands `. However, importing the ``app`` instance\nwithin the modules in your project is prone to circular import issues.\nWhen using the :doc:`app factory pattern ` or\nwriting reusable :doc:`blueprints ` or\n:doc:`extensions ` there won't be an ``app`` instance to\nimport at all.\n\nFlask solves this issue with the *application context*. Rather than\nreferring to an ``app`` directly, you use the :data:`current_app`\nproxy, which points to the application handling the current activity.\n\nFlask automatically *pushes* an application context when handling a\nrequest. View functions, error handlers, and other functions that run\nduring a request will have access to :data:`current_app`.\n\nFlask will also automatically push an app context when running CLI\ncommands registered with :attr:`Flask.cli` using ``@app.cli.command()``.\n\n\nLifetime of the Context\n-----------------------\n\nThe application context is created and destroyed as necessary. When a\nFlask application begins handling a request, it pushes an application\ncontext and a :doc:`request context `. When the request\nends it pops the request context then the application context.\nTypically, an application context will have the same lifetime as a\nrequest.\n\nSee :doc:`/reqcontext` for more information about how the contexts work\nand the full life cycle of a request.\n\n\nManually Push a Context\n-----------------------\n\nIf you try to access :data:`current_app`, or anything that uses it,\noutside an application context, you'll get this error message:\n\n.. code-block:: pytb\n\n RuntimeError: Working outside of application context.\n\n This typically means that you attempted to use functionality that\n needed to interface with the current application object in some way.\n To solve this, set up an application context with app.app_context().\n\nIf you see that error while configuring your application, such as when\ninitializing an extension, you can push a context manually since you\nhave direct access to the ``app``. Use :meth:`~Flask.app_context` in a\n``with`` block, and everything that runs in the block will have access\nto :data:`current_app`. ::\n\n def create_app():\n app = Flask(__name__)\n\n with app.app_context():\n init_db()\n\n return app\n\nIf you see that error somewhere else in your code not related to\nconfiguring the application, it most likely indicates that you should\nmove that code into a view function or CLI command.\n\n\nStoring Data\n------------\n\nThe application context is a good place to store common data during a\nrequest or CLI command. Flask provides the :data:`g object ` for this\npurpose. It is a simple namespace object that has the same lifetime as\nan application context.\n\n.. note::\n The ``g`` name stands for \"global\", but that is referring to the\n data being global *within a context*. The data on ``g`` is lost\n after the context ends, and it is not an appropriate place to store\n data between requests. Use the :data:`session` or a database to\n store data across requests.\n\nA common use for :data:`g` is to manage resources during a request.\n\n1. ``get_X()`` creates resource ``X`` if it does not exist, caching it\n as ``g.X``.\n2. ``teardown_X()`` closes or otherwise deallocates the resource if it\n exists. It is registered as a :meth:`~Flask.teardown_appcontext`\n handler.\n\nFor example, you can manage a database connection using this pattern::\n\n from flask import g\n\n def get_db():\n if 'db' not in g:\n g.db = connect_to_database()\n\n return g.db\n\n @app.teardown_appcontext\n def teardown_db(exception):\n db = g.pop('db', None)\n\n if db is not None:\n db.close()\n\nDuring a request, every call to ``get_db()`` will return the same\nconnection, and it will be closed automatically at the end of the\nrequest.\n\nYou can use :class:`~werkzeug.local.LocalProxy` to make a new context\nlocal from ``get_db()``::\n\n from werkzeug.local import LocalProxy\n db = LocalProxy(get_db)\n\nAccessing ``db`` will call ``get_db`` internally, in the same way that\n:data:`current_app` works.\n\n\nEvents and Signals\n------------------\n\nThe application will call functions registered with :meth:`~Flask.teardown_appcontext`\nwhen the application context is popped.\n\nThe following signals are sent: :data:`appcontext_pushed`,\n:data:`appcontext_tearing_down`, and :data:`appcontext_popped`.\n"},{"id":30,"name":"testing.rst","nodeType":"TextFile","path":"docs","text":"Testing Flask Applications\n==========================\n\nFlask provides utilities for testing an application. This documentation\ngoes over techniques for working with different parts of the application\nin tests.\n\nWe will use the `pytest`_ framework to set up and run our tests.\n\n.. code-block:: text\n\n $ pip install pytest\n\n.. _pytest: https://docs.pytest.org/\n\nThe :doc:`tutorial ` goes over how to write tests for\n100% coverage of the sample Flaskr blog application. See\n:doc:`the tutorial on tests ` for a detailed\nexplanation of specific tests for an application.\n\n\nIdentifying Tests\n-----------------\n\nTests are typically located in the ``tests`` folder. Tests are functions\nthat start with ``test_``, in Python modules that start with ``test_``.\nTests can also be further grouped in classes that start with ``Test``.\n\nIt can be difficult to know what to test. Generally, try to test the\ncode that you write, not the code of libraries that you use, since they\nare already tested. Try to extract complex behaviors as separate\nfunctions to test individually.\n\n\nFixtures\n--------\n\nPytest *fixtures* allow writing pieces of code that are reusable across\ntests. A simple fixture returns a value, but a fixture can also do\nsetup, yield a value, then do teardown. Fixtures for the application,\ntest client, and CLI runner are shown below, they can be placed in\n``tests/conftest.py``.\n\nIf you're using an\n:doc:`application factory `, define an ``app``\nfixture to create and configure an app instance. You can add code before\nand after the ``yield`` to set up and tear down other resources, such as\ncreating and clearing a database.\n\nIf you're not using a factory, you already have an app object you can\nimport and configure directly. You can still use an ``app`` fixture to\nset up and tear down resources.\n\n.. code-block:: python\n\n import pytest\n from my_project import create_app\n\n @pytest.fixture()\n def app():\n app = create_app()\n app.config.update({\n \"TESTING\": True,\n })\n\n # other setup can go here\n\n yield app\n\n # clean up / reset resources here\n\n\n @pytest.fixture()\n def client(app):\n return app.test_client()\n\n\n @pytest.fixture()\n def runner(app):\n return app.test_cli_runner()\n\n\nSending Requests with the Test Client\n-------------------------------------\n\nThe test client makes requests to the application without running a live\nserver. Flask's client extends\n:doc:`Werkzeug's client `, see those docs for additional\ninformation.\n\nThe ``client`` has methods that match the common HTTP request methods,\nsuch as ``client.get()`` and ``client.post()``. They take many arguments\nfor building the request; you can find the full documentation in\n:class:`~werkzeug.test.EnvironBuilder`. Typically you'll use ``path``,\n``query_string``, ``headers``, and ``data`` or ``json``.\n\nTo make a request, call the method the request should use with the path\nto the route to test. A :class:`~werkzeug.test.TestResponse` is returned\nto examine the response data. It has all the usual properties of a\nresponse object. You'll usually look at ``response.data``, which is the\nbytes returned by the view. If you want to use text, Werkzeug 2.1\nprovides ``response.text``, or use ``response.get_data(as_text=True)``.\n\n.. code-block:: python\n\n def test_request_example(client):\n response = client.get(\"/posts\")\n assert b\"

Hello, World!

\" in response.data\n\n\nPass a dict ``query_string={\"key\": \"value\", ...}`` to set arguments in\nthe query string (after the ``?`` in the URL). Pass a dict\n``headers={}`` to set request headers.\n\nTo send a request body in a POST or PUT request, pass a value to\n``data``. If raw bytes are passed, that exact body is used. Usually,\nyou'll pass a dict to set form data.\n\n\nForm Data\n~~~~~~~~~\n\nTo send form data, pass a dict to ``data``. The ``Content-Type`` header\nwill be set to ``multipart/form-data`` or\n``application/x-www-form-urlencoded`` automatically.\n\nIf a value is a file object opened for reading bytes (``\"rb\"`` mode), it\nwill be treated as an uploaded file. To change the detected filename and\ncontent type, pass a ``(file, filename, content_type)`` tuple. File\nobjects will be closed after making the request, so they do not need to\nuse the usual ``with open() as f:`` pattern.\n\nIt can be useful to store files in a ``tests/resources`` folder, then\nuse ``pathlib.Path`` to get files relative to the current test file.\n\n.. code-block:: python\n\n from pathlib import Path\n\n # get the resources folder in the tests folder\n resources = Path(__file__).parent / \"resources\"\n\n def test_edit_user(client):\n response = client.post(\"/user/2/edit\", data={\n \"name\": \"Flask\",\n \"theme\": \"dark\",\n \"picture\": (resources / \"picture.png\").open(\"rb\"),\n })\n assert response.status_code == 200\n\n\nJSON Data\n~~~~~~~~~\n\nTo send JSON data, pass an object to ``json``. The ``Content-Type``\nheader will be set to ``application/json`` automatically.\n\nSimilarly, if the response contains JSON data, the ``response.json``\nattribute will contain the deserialized object.\n\n.. code-block:: python\n\n def test_json_data(client):\n response = client.post(\"/graphql\", json={\n \"query\": \"\"\"\n query User($id: String!) {\n user(id: $id) {\n name\n theme\n picture_url\n }\n }\n \"\"\",\n variables={\"id\": 2},\n })\n assert response.json[\"data\"][\"user\"][\"name\"] == \"Flask\"\n\n\nFollowing Redirects\n-------------------\n\nBy default, the client does not make additional requests if the response\nis a redirect. By passing ``follow_redirects=True`` to a request method,\nthe client will continue to make requests until a non-redirect response\nis returned.\n\n:attr:`TestResponse.history ` is\na tuple of the responses that led up to the final response. Each\nresponse has a :attr:`~werkzeug.test.TestResponse.request` attribute\nwhich records the request that produced that response.\n\n.. code-block:: python\n\n def test_logout_redirect(client):\n response = client.get(\"/logout\")\n # Check that there was one redirect response.\n assert len(response.history) == 1\n # Check that the second request was to the index page.\n assert response.request.path == \"/index\"\n\n\nAccessing and Modifying the Session\n-----------------------------------\n\nTo access Flask's context variables, mainly\n:data:`~flask.session`, use the client in a ``with`` statement.\nThe app and request context will remain active *after* making a request,\nuntil the ``with`` block ends.\n\n.. code-block:: python\n\n from flask import session\n\n def test_access_session(client):\n with client:\n client.post(\"/auth/login\", data={\"username\": \"flask\"})\n # session is still accessible\n assert session[\"user_id\"] == 1\n\n # session is no longer accessible\n\nIf you want to access or set a value in the session *before* making a\nrequest, use the client's\n:meth:`~flask.testing.FlaskClient.session_transaction` method in a\n``with`` statement. It returns a session object, and will save the\nsession once the block ends.\n\n.. code-block:: python\n\n from flask import session\n\n def test_modify_session(client):\n with client.session_transaction() as session:\n # set a user id without going through the login route\n session[\"user_id\"] = 1\n\n # session is saved now\n\n response = client.get(\"/users/me\")\n assert response.json[\"username\"] == \"flask\"\n\n\n.. _testing-cli:\n\nRunning Commands with the CLI Runner\n------------------------------------\n\nFlask provides :meth:`~flask.Flask.test_cli_runner` to create a\n:class:`~flask.testing.FlaskCliRunner`, which runs CLI commands in\nisolation and captures the output in a :class:`~click.testing.Result`\nobject. Flask's runner extends :doc:`Click's runner `,\nsee those docs for additional information.\n\nUse the runner's :meth:`~flask.testing.FlaskCliRunner.invoke` method to\ncall commands in the same way they would be called with the ``flask``\ncommand from the command line.\n\n.. code-block:: python\n\n import click\n\n @app.cli.command(\"hello\")\n @click.option(\"--name\", default=\"World\")\n def hello_command(name):\n click.echo(f\"Hello, {name}!\")\n\n def test_hello_command(runner):\n result = runner.invoke(args=\"hello\")\n assert \"World\" in result.output\n\n result = runner.invoke(args=[\"hello\", \"--name\", \"Flask\"])\n assert \"Flask\" in result.output\n\n\nTests that depend on an Active Context\n--------------------------------------\n\nYou may have functions that are called from views or commands, that\nexpect an active :doc:`application context ` or\n:doc:`request context ` because they access ``request``,\n``session``, or ``current_app``. Rather than testing them by making a\nrequest or invoking the command, you can create and activate a context\ndirectly.\n\nUse ``with app.app_context()`` to push an application context. For\nexample, database extensions usually require an active app context to\nmake queries.\n\n.. code-block:: python\n\n def test_db_post_model(app):\n with app.app_context():\n post = db.session.query(Post).get(1)\n\nUse ``with app.test_request_context()`` to push a request context. It\ntakes the same arguments as the test client's request methods.\n\n.. code-block:: python\n\n def test_validate_user_edit(app):\n with app.test_request_context(\n \"/user/2/edit\", method=\"POST\", data={\"name\": \"\"}\n ):\n # call a function that accesses `request`\n messages = validate_edit_user()\n\n assert messages[\"name\"][0] == \"Name cannot be empty.\"\n\nCreating a test request context doesn't run any of the Flask dispatching\ncode, so ``before_request`` functions are not called. If you need to\ncall these, usually it's better to make a full request instead. However,\nit's possible to call them manually.\n\n.. code-block:: python\n\n def test_auth_token(app):\n with app.test_request_context(\"/user/2/edit\", headers={\"X-Auth-Token\": \"1\"}):\n app.preprocess_request()\n assert g.user.name == \"Flask\"\n"},{"id":31,"name":"proxy_fix.rst","nodeType":"TextFile","path":"docs/deploying","text":"Tell Flask it is Behind a Proxy\n===============================\n\nWhen using a reverse proxy, or many Python hosting platforms, the proxy\nwill intercept and forward all external requests to the local WSGI\nserver.\n\nFrom the WSGI server and Flask application's perspectives, requests are\nnow coming from the HTTP server to the local address, rather than from\nthe remote address to the external server address.\n\nHTTP servers should set ``X-Forwarded-`` headers to pass on the real\nvalues to the application. The application can then be told to trust and\nuse those values by wrapping it with the\n:doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug.\n\nThis middleware should only be used if the application is actually\nbehind a proxy, and should be configured with the number of proxies that\nare chained in front of it. Not all proxies set all the headers. Since\nincoming headers can be faked, you must set how many proxies are setting\neach header so the middleware knows what to trust.\n\n.. code-block:: python\n\n from werkzeug.middleware.proxy_fix import ProxyFix\n\n app.wsgi_app = ProxyFix(\n app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1\n )\n\nRemember, only apply this middleware if you are behind a proxy, and set\nthe correct number of proxies that set each header. It can be a security\nissue if you get this configuration wrong.\n"},{"id":32,"name":"deferredcallbacks.rst","nodeType":"TextFile","path":"docs/patterns","text":"Deferred Request Callbacks\n==========================\n\nOne of the design principles of Flask is that response objects are created and\npassed down a chain of potential callbacks that can modify them or replace\nthem. When the request handling starts, there is no response object yet. It is\ncreated as necessary either by a view function or by some other component in\nthe system.\n\nWhat happens if you want to modify the response at a point where the response\ndoes not exist yet? A common example for that would be a\n:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the\nresponse object.\n\nOne way is to avoid the situation. Very often that is possible. For instance\nyou can try to move that logic into a :meth:`~flask.Flask.after_request`\ncallback instead. However, sometimes moving code there makes it\nmore complicated or awkward to reason about.\n\nAs an alternative, you can use :func:`~flask.after_this_request` to register\ncallbacks that will execute after only the current request. This way you can\ndefer code execution from anywhere in the application, based on the current\nrequest.\n\nAt any time during a request, we can register a function to be called at the\nend of the request. For example you can remember the current language of the\nuser in a cookie in a :meth:`~flask.Flask.before_request` callback::\n\n from flask import request, after_this_request\n\n @app.before_request\n def detect_user_language():\n language = request.cookies.get('user_lang')\n\n if language is None:\n language = guess_language_from_request()\n\n # when the response exists, set a cookie with the language\n @after_this_request\n def remember_language(response):\n response.set_cookie('user_lang', language)\n return response\n\n g.language = language\n"},{"id":33,"name":"apache-httpd.rst","nodeType":"TextFile","path":"docs/deploying","text":"Apache httpd\n============\n\n`Apache httpd`_ is a fast, production level HTTP server. When serving\nyour application with one of the WSGI servers listed in :doc:`index`, it\nis often good or necessary to put a dedicated HTTP server in front of\nit. This \"reverse proxy\" can handle incoming requests, TLS, and other\nsecurity and performance concerns better than the WSGI server.\n\nhttpd can be installed using your system package manager, or a pre-built\nexecutable for Windows. Installing and running httpd itself is outside\nthe scope of this doc. This page outlines the basics of configuring\nhttpd to proxy your application. Be sure to read its documentation to\nunderstand what features are available.\n\n.. _Apache httpd: https://httpd.apache.org/\n\n\nDomain Name\n-----------\n\nAcquiring and configuring a domain name is outside the scope of this\ndoc. In general, you will buy a domain name from a registrar, pay for\nserver space with a hosting provider, and then point your registrar\nat the hosting provider's name servers.\n\nTo simulate this, you can also edit your ``hosts`` file, located at\n``/etc/hosts`` on Linux. Add a line that associates a name with the\nlocal IP.\n\nModern Linux systems may be configured to treat any domain name that\nends with ``.localhost`` like this without adding it to the ``hosts``\nfile.\n\n.. code-block:: python\n :caption: ``/etc/hosts``\n\n 127.0.0.1 hello.localhost\n\n\nConfiguration\n-------------\n\nThe httpd configuration is located at ``/etc/httpd/conf/httpd.conf`` on\nLinux. It may be different depending on your operating system. Check the\ndocs and look for ``httpd.conf``.\n\nRemove or comment out any existing ``DocumentRoot`` directive. Add the\nconfig lines below. We'll assume the WSGI server is listening locally at\n``http://127.0.0.1:8000``.\n\n.. code-block:: apache\n :caption: ``/etc/httpd/conf/httpd.conf``\n\n LoadModule proxy_module modules/mod_proxy.so\n LoadModule proxy_http_module modules/mod_proxy_http.so\n ProxyPass / http://127.0.0.1:8000/\n RequestHeader set X-Forwarded-Proto http\n RequestHeader set X-Forwarded-Prefix /\n\nThe ``LoadModule`` lines might already exist. If so, make sure they are\nuncommented instead of adding them manually.\n\nThen :doc:`proxy_fix` so that your application uses the ``X-Forwarded``\nheaders. ``X-Forwarded-For`` and ``X-Forwarded-Host`` are automatically\nset by ``ProxyPass``.\n"},{"id":34,"name":"mongoengine.rst","nodeType":"TextFile","path":"docs/patterns","text":"MongoDB with MongoEngine\n========================\n\nUsing a document database like MongoDB is a common alternative to\nrelational SQL databases. This pattern shows how to use\n`MongoEngine`_, a document mapper library, to integrate with MongoDB.\n\nA running MongoDB server and `Flask-MongoEngine`_ are required. ::\n\n pip install flask-mongoengine\n\n.. _MongoEngine: http://mongoengine.org\n.. _Flask-MongoEngine: https://flask-mongoengine.readthedocs.io\n\n\nConfiguration\n-------------\n\nBasic setup can be done by defining ``MONGODB_SETTINGS`` on\n``app.config`` and creating a ``MongoEngine`` instance. ::\n\n from flask import Flask\n from flask_mongoengine import MongoEngine\n\n app = Flask(__name__)\n app.config['MONGODB_SETTINGS'] = {\n \"db\": \"myapp\",\n }\n db = MongoEngine(app)\n\n\nMapping Documents\n-----------------\n\nTo declare a model that represents a Mongo document, create a class that\ninherits from ``Document`` and declare each of the fields. ::\n\n import mongoengine as me\n\n class Movie(me.Document):\n title = me.StringField(required=True)\n year = me.IntField()\n rated = me.StringField()\n director = me.StringField()\n actors = me.ListField()\n\nIf the document has nested fields, use ``EmbeddedDocument`` to\ndefined the fields of the embedded document and\n``EmbeddedDocumentField`` to declare it on the parent document. ::\n\n class Imdb(me.EmbeddedDocument):\n imdb_id = me.StringField()\n rating = me.DecimalField()\n votes = me.IntField()\n\n class Movie(me.Document):\n ...\n imdb = me.EmbeddedDocumentField(Imdb)\n\n\nCreating Data\n-------------\n\nInstantiate your document class with keyword arguments for the fields.\nYou can also assign values to the field attributes after instantiation.\nThen call ``doc.save()``. ::\n\n bttf = Movie(title=\"Back To The Future\", year=1985)\n bttf.actors = [\n \"Michael J. Fox\",\n \"Christopher Lloyd\"\n ]\n bttf.imdb = Imdb(imdb_id=\"tt0088763\", rating=8.5)\n bttf.save()\n\n\nQueries\n-------\n\nUse the class ``objects`` attribute to make queries. A keyword argument\nlooks for an equal value on the field. ::\n\n bttf = Movies.objects(title=\"Back To The Future\").get_or_404()\n\nQuery operators may be used by concatenating them with the field name\nusing a double-underscore. ``objects``, and queries returned by\ncalling it, are iterable. ::\n\n some_theron_movie = Movie.objects(actors__in=[\"Charlize Theron\"]).first()\n\n for recents in Movie.objects(year__gte=2017):\n print(recents.title)\n\n\nDocumentation\n-------------\n\nThere are many more ways to define and query documents with MongoEngine.\nFor more information, check out the `official documentation\n`_.\n\nFlask-MongoEngine adds helpful utilities on top of MongoEngine. Check\nout their `documentation `_ as well.\n"},{"id":35,"name":"gunicorn.rst","nodeType":"TextFile","path":"docs/deploying","text":"Gunicorn\n========\n\n`Gunicorn`_ is a pure Python WSGI server with simple configuration and\nmultiple worker implementations for performance tuning.\n\n* It tends to integrate easily with hosting platforms.\n* It does not support Windows (but does run on WSL).\n* It is easy to install as it does not require additional dependencies\n or compilation.\n* It has built-in async worker support using gevent or eventlet.\n\nThis page outlines the basics of running Gunicorn. Be sure to read its\n`documentation`_ and use ``gunicorn --help`` to understand what features\nare available.\n\n.. _Gunicorn: https://gunicorn.org/\n.. _documentation: https://docs.gunicorn.org/\n\n\nInstalling\n----------\n\nGunicorn is easy to install, as it does not require external\ndependencies or compilation. It runs on Windows only under WSL.\n\nCreate a virtualenv, install your application, then install\n``gunicorn``.\n\n.. code-block:: text\n\n $ cd hello-app\n $ python -m venv .venv\n $ . .venv/bin/activate\n $ pip install . # install your application\n $ pip install gunicorn\n\n\nRunning\n-------\n\nThe only required argument to Gunicorn tells it how to load your Flask\napplication. The syntax is ``{module_import}:{app_variable}``.\n``module_import`` is the dotted import name to the module with your\napplication. ``app_variable`` is the variable with the application. It\ncan also be a function call (with any arguments) if you're using the\napp factory pattern.\n\n.. code-block:: text\n\n # equivalent to 'from hello import app'\n $ gunicorn -w 4 'hello:app'\n\n # equivalent to 'from hello import create_app; create_app()'\n $ gunicorn -w 4 'hello:create_app()'\n\n Starting gunicorn 20.1.0\n Listening at: http://127.0.0.1:8000 (x)\n Using worker: sync\n Booting worker with pid: x\n Booting worker with pid: x\n Booting worker with pid: x\n Booting worker with pid: x\n\nThe ``-w`` option specifies the number of processes to run; a starting\nvalue could be ``CPU * 2``. The default is only 1 worker, which is\nprobably not what you want for the default worker type.\n\nLogs for each request aren't shown by default, only worker info and\nerrors are shown. To show access logs on stdout, use the\n``--access-logfile=-`` option.\n\n\nBinding Externally\n------------------\n\nGunicorn should not be run as root because it would cause your\napplication code to run as root, which is not secure. However, this\nmeans it will not be possible to bind to port 80 or 443. Instead, a\nreverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used\nin front of Gunicorn.\n\nYou can bind to all external IPs on a non-privileged port using the\n``-b 0.0.0.0`` option. Don't do this when using a reverse proxy setup,\notherwise it will be possible to bypass the proxy.\n\n.. code-block:: text\n\n $ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()'\n Listening at: http://0.0.0.0:8000 (x)\n\n``0.0.0.0`` is not a valid address to navigate to, you'd use a specific\nIP address in your browser.\n\n\nAsync with gevent or eventlet\n-----------------------------\n\nThe default sync worker is appropriate for many use cases. If you need\nasynchronous support, Gunicorn provides workers using either `gevent`_\nor `eventlet`_. This is not the same as Python's ``async/await``, or the\nASGI server spec. You must actually use gevent/eventlet in your own code\nto see any benefit to using the workers.\n\nWhen using either gevent or eventlet, greenlet>=1.0 is required,\notherwise context locals such as ``request`` will not work as expected.\nWhen using PyPy, PyPy>=7.3.7 is required.\n\nTo use gevent:\n\n.. code-block:: text\n\n $ gunicorn -k gevent 'hello:create_app()'\n Starting gunicorn 20.1.0\n Listening at: http://127.0.0.1:8000 (x)\n Using worker: gevent\n Booting worker with pid: x\n\nTo use eventlet:\n\n.. code-block:: text\n\n $ gunicorn -k eventlet 'hello:create_app()'\n Starting gunicorn 20.1.0\n Listening at: http://127.0.0.1:8000 (x)\n Using worker: eventlet\n Booting worker with pid: x\n\n.. _gevent: https://www.gevent.org/\n.. _eventlet: https://eventlet.net/\n"},{"id":36,"name":"waitress.rst","nodeType":"TextFile","path":"docs/deploying","text":"Waitress\n========\n\n`Waitress`_ is a pure Python WSGI server.\n\n* It is easy to configure.\n* It supports Windows directly.\n* It is easy to install as it does not require additional dependencies\n or compilation.\n* It does not support streaming requests, full request data is always\n buffered.\n* It uses a single process with multiple thread workers.\n\nThis page outlines the basics of running Waitress. Be sure to read its\ndocumentation and ``waitress-serve --help`` to understand what features\nare available.\n\n.. _Waitress: https://docs.pylonsproject.org/projects/waitress/\n\n\nInstalling\n----------\n\nCreate a virtualenv, install your application, then install\n``waitress``.\n\n.. code-block:: text\n\n $ cd hello-app\n $ python -m venv .venv\n $ . .venv/bin/activate\n $ pip install . # install your application\n $ pip install waitress\n\n\nRunning\n-------\n\nThe only required argument to ``waitress-serve`` tells it how to load\nyour Flask application. The syntax is ``{module}:{app}``. ``module`` is\nthe dotted import name to the module with your application. ``app`` is\nthe variable with the application. If you're using the app factory\npattern, use ``--call {module}:{factory}`` instead.\n\n.. code-block:: text\n\n # equivalent to 'from hello import app'\n $ waitress-serve --host 127.0.0.1 hello:app\n\n # equivalent to 'from hello import create_app; create_app()'\n $ waitress-serve --host 127.0.0.1 --call hello:create_app\n\n Serving on http://127.0.0.1:8080\n\nThe ``--host`` option binds the server to local ``127.0.0.1`` only.\n\nLogs for each request aren't shown, only errors are shown. Logging can\nbe configured through the Python interface instead of the command line.\n\n\nBinding Externally\n------------------\n\nWaitress should not be run as root because it would cause your\napplication code to run as root, which is not secure. However, this\nmeans it will not be possible to bind to port 80 or 443. Instead, a\nreverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used\nin front of Waitress.\n\nYou can bind to all external IPs on a non-privileged port by not\nspecifying the ``--host`` option. Don't do this when using a revers\nproxy setup, otherwise it will be possible to bypass the proxy.\n\n``0.0.0.0`` is not a valid address to navigate to, you'd use a specific\nIP address in your browser.\n"},{"id":37,"name":"typing.in","nodeType":"TextFile","path":"requirements","text":"mypy\ntypes-contextvars\ntypes-dataclasses\ntypes-setuptools\ncryptography\n"},{"id":38,"name":"signals.rst","nodeType":"TextFile","path":"docs","text":"Signals\n=======\n\nSignals are a lightweight way to notify subscribers of certain events during the\nlifecycle of the application and each request. When an event occurs, it emits the\nsignal, which calls each subscriber.\n\nSignals are implemented by the `Blinker`_ library. See its documentation for detailed\ninformation. Flask provides some built-in signals. Extensions may provide their own.\n\nMany signals mirror Flask's decorator-based callbacks with similar names. For example,\nthe :data:`.request_started` signal is similar to the :meth:`~.Flask.before_request`\ndecorator. The advantage of signals over handlers is that they can be subscribed to\ntemporarily, and can't directly affect the application. This is useful for testing,\nmetrics, auditing, and more. For example, if you want to know what templates were\nrendered at what parts of what requests, there is a signal that will notify you of that\ninformation.\n\n\nCore Signals\n------------\n\nSee :ref:`core-signals-list` for a list of all built-in signals. The :doc:`lifecycle`\npage also describes the order that signals and decorators execute.\n\n\nSubscribing to Signals\n----------------------\n\nTo subscribe to a signal, you can use the\n:meth:`~blinker.base.Signal.connect` method of a signal. The first\nargument is the function that should be called when the signal is emitted,\nthe optional second argument specifies a sender. To unsubscribe from a\nsignal, you can use the :meth:`~blinker.base.Signal.disconnect` method.\n\nFor all core Flask signals, the sender is the application that issued the\nsignal. When you subscribe to a signal, be sure to also provide a sender\nunless you really want to listen for signals from all applications. This is\nespecially true if you are developing an extension.\n\nFor example, here is a helper context manager that can be used in a unit test\nto determine which templates were rendered and what variables were passed\nto the template::\n\n from flask import template_rendered\n from contextlib import contextmanager\n\n @contextmanager\n def captured_templates(app):\n recorded = []\n def record(sender, template, context, **extra):\n recorded.append((template, context))\n template_rendered.connect(record, app)\n try:\n yield recorded\n finally:\n template_rendered.disconnect(record, app)\n\nThis can now easily be paired with a test client::\n\n with captured_templates(app) as templates:\n rv = app.test_client().get('/')\n assert rv.status_code == 200\n assert len(templates) == 1\n template, context = templates[0]\n assert template.name == 'index.html'\n assert len(context['items']) == 10\n\nMake sure to subscribe with an extra ``**extra`` argument so that your\ncalls don't fail if Flask introduces new arguments to the signals.\n\nAll the template rendering in the code issued by the application `app`\nin the body of the ``with`` block will now be recorded in the `templates`\nvariable. Whenever a template is rendered, the template object as well as\ncontext are appended to it.\n\nAdditionally there is a convenient helper method\n(:meth:`~blinker.base.Signal.connected_to`) that allows you to\ntemporarily subscribe a function to a signal with a context manager on\nits own. Because the return value of the context manager cannot be\nspecified that way, you have to pass the list in as an argument::\n\n from flask import template_rendered\n\n def captured_templates(app, recorded, **extra):\n def record(sender, template, context):\n recorded.append((template, context))\n return template_rendered.connected_to(record, app)\n\nThe example above would then look like this::\n\n templates = []\n with captured_templates(app, templates, **extra):\n ...\n template, context = templates[0]\n\nCreating Signals\n----------------\n\nIf you want to use signals in your own application, you can use the\nblinker library directly. The most common use case are named signals in a\ncustom :class:`~blinker.base.Namespace`.. This is what is recommended\nmost of the time::\n\n from blinker import Namespace\n my_signals = Namespace()\n\nNow you can create new signals like this::\n\n model_saved = my_signals.signal('model-saved')\n\nThe name for the signal here makes it unique and also simplifies\ndebugging. You can access the name of the signal with the\n:attr:`~blinker.base.NamedSignal.name` attribute.\n\n.. _signals-sending:\n\nSending Signals\n---------------\n\nIf you want to emit a signal, you can do so by calling the\n:meth:`~blinker.base.Signal.send` method. It accepts a sender as first\nargument and optionally some keyword arguments that are forwarded to the\nsignal subscribers::\n\n class Model(object):\n ...\n\n def save(self):\n model_saved.send(self)\n\nTry to always pick a good sender. If you have a class that is emitting a\nsignal, pass ``self`` as sender. If you are emitting a signal from a random\nfunction, you can pass ``current_app._get_current_object()`` as sender.\n\n.. admonition:: Passing Proxies as Senders\n\n Never pass :data:`~flask.current_app` as sender to a signal. Use\n ``current_app._get_current_object()`` instead. The reason for this is\n that :data:`~flask.current_app` is a proxy and not the real application\n object.\n\n\nSignals and Flask's Request Context\n-----------------------------------\n\nSignals fully support :doc:`reqcontext` when receiving signals.\nContext-local variables are consistently available between\n:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can\nrely on :class:`flask.g` and others as needed. Note the limitations described\nin :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal.\n\n\nDecorator Based Signal Subscriptions\n------------------------------------\n\nYou can also easily subscribe to signals by using the\n:meth:`~blinker.base.NamedSignal.connect_via` decorator::\n\n from flask import template_rendered\n\n @template_rendered.connect_via(app)\n def when_template_rendered(sender, template, context, **extra):\n print(f'Template {template.name} is rendered with {context}')\n\n\n.. _blinker: https://pypi.org/project/blinker/\n"},{"id":39,"name":".readthedocs.yaml","nodeType":"TextFile","path":"","text":"version: 2\nbuild:\n os: ubuntu-20.04\n tools:\n python: \"3.10\"\npython:\n install:\n - requirements: requirements/docs.txt\n - method: pip\n path: .\nsphinx:\n builder: dirhtml\n fail_on_warning: true\n"},{"id":40,"name":"tests/test_apps/cliapp/inner1/inner2","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/cliapp/inner1/inner2","id":41,"nodeType":"File","text":""},{"id":42,"name":"config.json","nodeType":"TextFile","path":"tests/static","text":"{\n \"TEST_KEY\": \"foo\",\n \"SECRET_KEY\": \"config\"\n}\n"},{"id":43,"name":"tests/test_apps/cliapp/inner1","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/cliapp/inner1","id":44,"nodeType":"File","text":"from flask import Flask\n\napplication = Flask(__name__)\n"},{"id":45,"name":"wtforms.rst","nodeType":"TextFile","path":"docs/patterns","text":"Form Validation with WTForms\n============================\n\nWhen you have to work with form data submitted by a browser view, code\nquickly becomes very hard to read. There are libraries out there designed\nto make this process easier to manage. One of them is `WTForms`_ which we\nwill handle here. If you find yourself in the situation of having many\nforms, you might want to give it a try.\n\nWhen you are working with WTForms you have to define your forms as classes\nfirst. I recommend breaking up the application into multiple modules\n(:doc:`packages`) for that and adding a separate module for the\nforms.\n\n.. admonition:: Getting the most out of WTForms with an Extension\n\n The `Flask-WTF`_ extension expands on this pattern and adds a\n few little helpers that make working with forms and Flask more\n fun. You can get it from `PyPI\n `_.\n\n.. _Flask-WTF: https://flask-wtf.readthedocs.io/\n\nThe Forms\n---------\n\nThis is an example form for a typical registration page::\n\n from wtforms import Form, BooleanField, StringField, PasswordField, validators\n\n class RegistrationForm(Form):\n username = StringField('Username', [validators.Length(min=4, max=25)])\n email = StringField('Email Address', [validators.Length(min=6, max=35)])\n password = PasswordField('New Password', [\n validators.DataRequired(),\n validators.EqualTo('confirm', message='Passwords must match')\n ])\n confirm = PasswordField('Repeat Password')\n accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])\n\nIn the View\n-----------\n\nIn the view function, the usage of this form looks like this::\n\n @app.route('/register', methods=['GET', 'POST'])\n def register():\n form = RegistrationForm(request.form)\n if request.method == 'POST' and form.validate():\n user = User(form.username.data, form.email.data,\n form.password.data)\n db_session.add(user)\n flash('Thanks for registering')\n return redirect(url_for('login'))\n return render_template('register.html', form=form)\n\nNotice we're implying that the view is using SQLAlchemy here\n(:doc:`sqlalchemy`), but that's not a requirement, of course. Adapt\nthe code as necessary.\n\nThings to remember:\n\n1. create the form from the request :attr:`~flask.request.form` value if\n the data is submitted via the HTTP ``POST`` method and\n :attr:`~flask.request.args` if the data is submitted as ``GET``.\n2. to validate the data, call the :func:`~wtforms.form.Form.validate`\n method, which will return ``True`` if the data validates, ``False``\n otherwise.\n3. to access individual values from the form, access `form..data`.\n\nForms in Templates\n------------------\n\nNow to the template side. When you pass the form to the templates, you can\neasily render them there. Look at the following example template to see\nhow easy this is. WTForms does half the form generation for us already.\nTo make it even nicer, we can write a macro that renders a field with\nlabel and a list of errors if there are any.\n\nHere's an example :file:`_formhelpers.html` template with such a macro:\n\n.. sourcecode:: html+jinja\n\n {% macro render_field(field) %}\n
{{ field.label }}\n
{{ field(**kwargs)|safe }}\n {% if field.errors %}\n
    \n {% for error in field.errors %}\n
  • {{ error }}
  • \n {% endfor %}\n
\n {% endif %}\n
\n {% endmacro %}\n\nThis macro accepts a couple of keyword arguments that are forwarded to\nWTForm's field function, which renders the field for us. The keyword\narguments will be inserted as HTML attributes. So, for example, you can\ncall ``render_field(form.username, class='username')`` to add a class to\nthe input element. Note that WTForms returns standard Python strings,\nso we have to tell Jinja2 that this data is already HTML-escaped with\nthe ``|safe`` filter.\n\nHere is the :file:`register.html` template for the function we used above, which\ntakes advantage of the :file:`_formhelpers.html` template:\n\n.. sourcecode:: html+jinja\n\n {% from \"_formhelpers.html\" import render_field %}\n
\n
\n {{ render_field(form.username) }}\n {{ render_field(form.email) }}\n {{ render_field(form.password) }}\n {{ render_field(form.confirm) }}\n {{ render_field(form.accept_tos) }}\n
\n

\n

\n\nFor more information about WTForms, head over to the `WTForms\nwebsite`_.\n\n.. _WTForms: https://wtforms.readthedocs.io/\n.. _WTForms website: https://wtforms.readthedocs.io/\n"},{"id":46,"name":"tests/test_apps/helloworld","nodeType":"Package"},{"fileName":"wsgi.py","filePath":"tests/test_apps/helloworld","id":47,"nodeType":"File","text":"from hello import app # noqa: F401\n"},{"id":48,"name":"uwsgi.rst","nodeType":"TextFile","path":"docs/deploying","text":"uWSGI\n=====\n\n`uWSGI`_ is a fast, compiled server suite with extensive configuration\nand capabilities beyond a basic server.\n\n* It can be very performant due to being a compiled program.\n* It is complex to configure beyond the basic application, and has so\n many options that it can be difficult for beginners to understand.\n* It does not support Windows (but does run on WSL).\n* It requires a compiler to install in some cases.\n\nThis page outlines the basics of running uWSGI. Be sure to read its\ndocumentation to understand what features are available.\n\n.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/\n\n\nInstalling\n----------\n\nuWSGI has multiple ways to install it. The most straightforward is to\ninstall the ``pyuwsgi`` package, which provides precompiled wheels for\ncommon platforms. However, it does not provide SSL support, which can be\nprovided with a reverse proxy instead.\n\nCreate a virtualenv, install your application, then install ``pyuwsgi``.\n\n.. code-block:: text\n\n $ cd hello-app\n $ python -m venv .venv\n $ . .venv/bin/activate\n $ pip install . # install your application\n $ pip install pyuwsgi\n\nIf you have a compiler available, you can install the ``uwsgi`` package\ninstead. Or install the ``pyuwsgi`` package from sdist instead of wheel.\nEither method will include SSL support.\n\n.. code-block:: text\n\n $ pip install uwsgi\n\n # or\n $ pip install --no-binary pyuwsgi pyuwsgi\n\n\nRunning\n-------\n\nThe most basic way to run uWSGI is to tell it to start an HTTP server\nand import your application.\n\n.. code-block:: text\n\n $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app\n\n *** Starting uWSGI 2.0.20 (64bit) on [x] ***\n *** Operational MODE: preforking ***\n mounting hello:app on /\n spawned uWSGI master process (pid: x)\n spawned uWSGI worker 1 (pid: x, cores: 1)\n spawned uWSGI worker 2 (pid: x, cores: 1)\n spawned uWSGI worker 3 (pid: x, cores: 1)\n spawned uWSGI worker 4 (pid: x, cores: 1)\n spawned uWSGI http 1 (pid: x)\n\nIf you're using the app factory pattern, you'll need to create a small\nPython file to create the app, then point uWSGI at that.\n\n.. code-block:: python\n :caption: ``wsgi.py``\n\n from hello import create_app\n\n app = create_app()\n\n.. code-block:: text\n\n $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app\n\nThe ``--http`` option starts an HTTP server at 127.0.0.1 port 8000. The\n``--master`` option specifies the standard worker manager. The ``-p``\noption starts 4 worker processes; a starting value could be ``CPU * 2``.\nThe ``-w`` option tells uWSGI how to import your application\n\n\nBinding Externally\n------------------\n\nuWSGI should not be run as root with the configuration shown in this doc\nbecause it would cause your application code to run as root, which is\nnot secure. However, this means it will not be possible to bind to port\n80 or 443. Instead, a reverse proxy such as :doc:`nginx` or\n:doc:`apache-httpd` should be used in front of uWSGI. It is possible to\nrun uWSGI as root securely, but that is beyond the scope of this doc.\n\nuWSGI has optimized integration with `Nginx uWSGI`_ and\n`Apache mod_proxy_uwsgi`_, and possibly other servers, instead of using\na standard HTTP proxy. That configuration is beyond the scope of this\ndoc, see the links for more information.\n\n.. _Nginx uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/Nginx.html\n.. _Apache mod_proxy_uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/Apache.html#mod-proxy-uwsgi\n\nYou can bind to all external IPs on a non-privileged port using the\n``--http 0.0.0.0:8000`` option. Don't do this when using a reverse proxy\nsetup, otherwise it will be possible to bypass the proxy.\n\n.. code-block:: text\n\n $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app\n\n``0.0.0.0`` is not a valid address to navigate to, you'd use a specific\nIP address in your browser.\n\n\nAsync with gevent\n-----------------\n\nThe default sync worker is appropriate for many use cases. If you need\nasynchronous support, uWSGI provides a `gevent`_ worker. This is not the\nsame as Python's ``async/await``, or the ASGI server spec. You must\nactually use gevent in your own code to see any benefit to using the\nworker.\n\nWhen using gevent, greenlet>=1.0 is required, otherwise context locals\nsuch as ``request`` will not work as expected. When using PyPy,\nPyPy>=7.3.7 is required.\n\n.. code-block:: text\n\n $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app\n\n *** Starting uWSGI 2.0.20 (64bit) on [x] ***\n *** Operational MODE: async ***\n mounting hello:app on /\n spawned uWSGI master process (pid: x)\n spawned uWSGI worker 1 (pid: x, cores: 100)\n spawned uWSGI http 1 (pid: x)\n *** running gevent loop engine [addr:x] ***\n\n\n.. _gevent: https://www.gevent.org/\n"},{"id":49,"name":"tests-pallets-min.txt","nodeType":"TextFile","path":"requirements","text":"# SHA1:575f86f45391b662630a6080f0a12676215eb0cf\n#\n# This file is autogenerated by pip-compile-multi\n# To update, run:\n#\n# pip-compile-multi\n#\nblinker==1.6.2\n # via -r requirements/tests-pallets-min.in\nclick==8.0.0\n # via -r requirements/tests-pallets-min.in\nitsdangerous==2.0.0\n # via -r requirements/tests-pallets-min.in\njinja2==3.0.0\n # via -r requirements/tests-pallets-min.in\nmarkupsafe==2.0.0\n # via\n # -r requirements/tests-pallets-min.in\n # jinja2\nwerkzeug==2.0.0\n # via -r requirements/tests-pallets-min.in\n"},{"id":50,"name":"tests/templates","nodeType":"Package"},{"id":51,"name":"context_template.html","nodeType":"TextFile","path":"tests/templates","text":"

{{ value }}|{{ injected_value }}\n"},{"id":52,"name":"index.html","nodeType":"TextFile","path":"tests/static","text":"

Hello World!

\n"},{"id":53,"name":"tests.in","nodeType":"TextFile","path":"requirements","text":"pytest\nasgiref\ngreenlet ; python_version < \"3.11\"\npython-dotenv>=1; python_version >= \"3.8\"\n"},{"id":54,"name":"templating.rst","nodeType":"TextFile","path":"docs","text":"Templates\n=========\n\nFlask leverages Jinja2 as its template engine. You are obviously free to use\na different template engine, but you still have to install Jinja2 to run\nFlask itself. This requirement is necessary to enable rich extensions.\nAn extension can depend on Jinja2 being present.\n\nThis section only gives a very quick introduction into how Jinja2\nis integrated into Flask. If you want information on the template\nengine's syntax itself, head over to the official `Jinja2 Template\nDocumentation `_ for\nmore information.\n\nJinja Setup\n-----------\n\nUnless customized, Jinja2 is configured by Flask as follows:\n\n- autoescaping is enabled for all templates ending in ``.html``,\n ``.htm``, ``.xml``, ``.xhtml``, as well as ``.svg`` when using\n :func:`~flask.templating.render_template`.\n- autoescaping is enabled for all strings when using\n :func:`~flask.templating.render_template_string`.\n- a template has the ability to opt in/out autoescaping with the\n ``{% autoescape %}`` tag.\n- Flask inserts a couple of global functions and helpers into the\n Jinja2 context, additionally to the values that are present by\n default.\n\nStandard Context\n----------------\n\nThe following global variables are available within Jinja2 templates\nby default:\n\n.. data:: config\n :noindex:\n\n The current configuration object (:data:`flask.Flask.config`)\n\n .. versionadded:: 0.6\n\n .. versionchanged:: 0.10\n This is now always available, even in imported templates.\n\n.. data:: request\n :noindex:\n\n The current request object (:class:`flask.request`). This variable is\n unavailable if the template was rendered without an active request\n context.\n\n.. data:: session\n :noindex:\n\n The current session object (:class:`flask.session`). This variable\n is unavailable if the template was rendered without an active request\n context.\n\n.. data:: g\n :noindex:\n\n The request-bound object for global variables (:data:`flask.g`). This\n variable is unavailable if the template was rendered without an active\n request context.\n\n.. function:: url_for\n :noindex:\n\n The :func:`flask.url_for` function.\n\n.. function:: get_flashed_messages\n :noindex:\n\n The :func:`flask.get_flashed_messages` function.\n\n.. admonition:: The Jinja Context Behavior\n\n These variables are added to the context of variables, they are not\n global variables. The difference is that by default these will not\n show up in the context of imported templates. This is partially caused\n by performance considerations, partially to keep things explicit.\n\n What does this mean for you? If you have a macro you want to import,\n that needs to access the request object you have two possibilities:\n\n 1. you explicitly pass the request to the macro as parameter, or\n the attribute of the request object you are interested in.\n 2. you import the macro \"with context\".\n\n Importing with context looks like this:\n\n .. sourcecode:: jinja\n\n {% from '_helpers.html' import my_macro with context %}\n\n\nControlling Autoescaping\n------------------------\n\nAutoescaping is the concept of automatically escaping special characters\nfor you. Special characters in the sense of HTML (or XML, and thus XHTML)\nare ``&``, ``>``, ``<``, ``\"`` as well as ``'``. Because these characters\ncarry specific meanings in documents on their own you have to replace them\nby so called \"entities\" if you want to use them for text. Not doing so\nwould not only cause user frustration by the inability to use these\ncharacters in text, but can also lead to security problems. (see\n:ref:`security-xss`)\n\nSometimes however you will need to disable autoescaping in templates.\nThis can be the case if you want to explicitly inject HTML into pages, for\nexample if they come from a system that generates secure HTML like a\nmarkdown to HTML converter.\n\nThere are three ways to accomplish that:\n\n- In the Python code, wrap the HTML string in a :class:`~markupsafe.Markup`\n object before passing it to the template. This is in general the\n recommended way.\n- Inside the template, use the ``|safe`` filter to explicitly mark a\n string as safe HTML (``{{ myvariable|safe }}``)\n- Temporarily disable the autoescape system altogether.\n\nTo disable the autoescape system in templates, you can use the ``{%\nautoescape %}`` block:\n\n.. sourcecode:: html+jinja\n\n {% autoescape false %}\n

autoescaping is disabled here\n

{{ will_not_be_escaped }}\n {% endautoescape %}\n\nWhenever you do this, please be very cautious about the variables you are\nusing in this block.\n\n.. _registering-filters:\n\nRegistering Filters\n-------------------\n\nIf you want to register your own filters in Jinja2 you have two ways to do\nthat. You can either put them by hand into the\n:attr:`~flask.Flask.jinja_env` of the application or use the\n:meth:`~flask.Flask.template_filter` decorator.\n\nThe two following examples work the same and both reverse an object::\n\n @app.template_filter('reverse')\n def reverse_filter(s):\n return s[::-1]\n\n def reverse_filter(s):\n return s[::-1]\n app.jinja_env.filters['reverse'] = reverse_filter\n\nIn case of the decorator the argument is optional if you want to use the\nfunction name as name of the filter. Once registered, you can use the filter\nin your templates in the same way as Jinja2's builtin filters, for example if\nyou have a Python list in context called `mylist`::\n\n {% for x in mylist | reverse %}\n {% endfor %}\n\n\nContext Processors\n------------------\n\nTo inject new variables automatically into the context of a template,\ncontext processors exist in Flask. Context processors run before the\ntemplate is rendered and have the ability to inject new values into the\ntemplate context. A context processor is a function that returns a\ndictionary. The keys and values of this dictionary are then merged with\nthe template context, for all templates in the app::\n\n @app.context_processor\n def inject_user():\n return dict(user=g.user)\n\nThe context processor above makes a variable called `user` available in\nthe template with the value of `g.user`. This example is not very\ninteresting because `g` is available in templates anyways, but it gives an\nidea how this works.\n\nVariables are not limited to values; a context processor can also make\nfunctions available to templates (since Python allows passing around\nfunctions)::\n\n @app.context_processor\n def utility_processor():\n def format_price(amount, currency=\"€\"):\n return f\"{amount:.2f}{currency}\"\n return dict(format_price=format_price)\n\nThe context processor above makes the `format_price` function available to all\ntemplates::\n\n {{ format_price(0.33) }}\n\nYou could also build `format_price` as a template filter (see\n:ref:`registering-filters`), but this demonstrates how to pass functions in a\ncontext processor.\n\nStreaming\n---------\n\nIt can be useful to not render the whole template as one complete\nstring, instead render it as a stream, yielding smaller incremental\nstrings. This can be used for streaming HTML in chunks to speed up\ninitial page load, or to save memory when rendering a very large\ntemplate.\n\nThe Jinja2 template engine supports rendering a template piece\nby piece, returning an iterator of strings. Flask provides the\n:func:`~flask.stream_template` and :func:`~flask.stream_template_string`\nfunctions to make this easier to use.\n\n.. code-block:: python\n\n from flask import stream_template\n\n @app.get(\"/timeline\")\n def timeline():\n return stream_template(\"timeline.html\")\n\nThese functions automatically apply the\n:func:`~flask.stream_with_context` wrapper if a request is active, so\nthat it remains available in the template.\n"},{"id":55,"name":"tests/test_apps/blueprintapp/apps","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/blueprintapp/apps","id":56,"nodeType":"File","text":""},{"fileName":"typing_error_handler.py","filePath":"tests/typing","id":57,"nodeType":"File","text":"from __future__ import annotations\n\nfrom http import HTTPStatus\n\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import NotFound\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\n@app.errorhandler(400)\n@app.errorhandler(HTTPStatus.BAD_REQUEST)\n@app.errorhandler(BadRequest)\ndef handle_400(e: BadRequest) -> str:\n return \"\"\n\n\n@app.errorhandler(ValueError)\ndef handle_custom(e: ValueError) -> str:\n return \"\"\n\n\n@app.errorhandler(ValueError)\ndef handle_accept_base(e: Exception) -> str:\n return \"\"\n\n\n@app.errorhandler(BadRequest)\n@app.errorhandler(404)\ndef handle_multiple(e: BadRequest | NotFound) -> str:\n return \"\"\n"},{"id":58,"name":"examples/tutorial/flaskr/templates/auth","nodeType":"Package"},{"id":59,"name":"register.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates/auth","text":"{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}Register{% endblock %}

\n{% endblock %}\n\n{% block content %}\n
\n \n \n \n \n \n
\n{% endblock %}\n"},{"id":60,"name":"examples/tutorial/flaskr","nodeType":"Package"},{"fileName":"__init__.py","filePath":"examples/tutorial/flaskr","id":61,"nodeType":"File","text":"import os\n\nfrom flask import Flask\n\n\ndef create_app(test_config=None):\n \"\"\"Create and configure an instance of the Flask application.\"\"\"\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n # a default secret that should be overridden by instance config\n SECRET_KEY=\"dev\",\n # store the database in the instance folder\n DATABASE=os.path.join(app.instance_path, \"flaskr.sqlite\"),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile(\"config.py\", silent=True)\n else:\n # load the test config if passed in\n app.config.update(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n @app.route(\"/hello\")\n def hello():\n return \"Hello, World!\"\n\n # register the database commands\n from flaskr import db\n\n db.init_app(app)\n\n # apply the blueprints to the app\n from flaskr import auth, blog\n\n app.register_blueprint(auth.bp)\n app.register_blueprint(blog.bp)\n\n # make url_for('index') == url_for('blog.index')\n # in another app, you might define a separate main index here with\n # app.route, while giving the blog blueprint a url_prefix, but for\n # the tutorial the blog will be the main index\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n return app\n"},{"id":62,"name":"javascript.rst","nodeType":"TextFile","path":"docs/patterns","text":"JavaScript, ``fetch``, and JSON\n===============================\n\nYou may want to make your HTML page dynamic, by changing data without\nreloading the entire page. Instead of submitting an HTML ``
`` and\nperforming a redirect to re-render the template, you can add\n`JavaScript`_ that calls |fetch|_ and replaces content on the page.\n\n|fetch|_ is the modern, built-in JavaScript solution to making\nrequests from a page. You may have heard of other \"AJAX\" methods and\nlibraries, such as |XHR|_ or `jQuery`_. These are no longer needed in\nmodern browsers, although you may choose to use them or another library\ndepending on your application's requirements. These docs will only focus\non built-in JavaScript features.\n\n.. _JavaScript: https://developer.mozilla.org/Web/JavaScript\n.. |fetch| replace:: ``fetch()``\n.. _fetch: https://developer.mozilla.org/Web/API/Fetch_API\n.. |XHR| replace:: ``XMLHttpRequest()``\n.. _XHR: https://developer.mozilla.org/Web/API/XMLHttpRequest\n.. _jQuery: https://jquery.com/\n\n\nRendering Templates\n-------------------\n\nIt is important to understand the difference between templates and\nJavaScript. Templates are rendered on the server, before the response is\nsent to the user's browser. JavaScript runs in the user's browser, after\nthe template is rendered and sent. Therefore, it is impossible to use\nJavaScript to affect how the Jinja template is rendered, but it is\npossible to render data into the JavaScript that will run.\n\nTo provide data to JavaScript when rendering the template, use the\n:func:`~jinja-filters.tojson` filter in a ``\n\nA less common pattern is to add the data to a ``data-`` attribute on an\nHTML tag. In this case, you must use single quotes around the value, not\ndouble quotes, otherwise you will produce invalid or unsafe HTML.\n\n.. code-block:: jinja\n\n
\n\n\nGenerating URLs\n---------------\n\nThe other way to get data from the server to JavaScript is to make a\nrequest for it. First, you need to know the URL to request.\n\nThe simplest way to generate URLs is to continue to use\n:func:`~flask.url_for` when rendering the template. For example:\n\n.. code-block:: javascript\n\n const user_url = {{ url_for(\"user\", id=current_user.id)|tojson }}\n fetch(user_url).then(...)\n\nHowever, you might need to generate a URL based on information you only\nknow in JavaScript. As discussed above, JavaScript runs in the user's\nbrowser, not as part of the template rendering, so you can't use\n``url_for`` at that point.\n\nIn this case, you need to know the \"root URL\" under which your\napplication is served. In simple setups, this is ``/``, but it might\nalso be something else, like ``https://example.com/myapp/``.\n\nA simple way to tell your JavaScript code about this root is to set it\nas a global variable when rendering the template. Then you can use it\nwhen generating URLs from JavaScript.\n\n.. code-block:: javascript\n\n const SCRIPT_ROOT = {{ request.script_root|tojson }}\n let user_id = ... // do something to get a user id from the page\n let user_url = `${SCRIPT_ROOT}/user/${user_id}`\n fetch(user_url).then(...)\n\n\nMaking a Request with ``fetch``\n-------------------------------\n\n|fetch|_ takes two arguments, a URL and an object with other options,\nand returns a |Promise|_. We won't cover all the available options, and\nwill only use ``then()`` on the promise, not other callbacks or\n``await`` syntax. Read the linked MDN docs for more information about\nthose features.\n\nBy default, the GET method is used. If the response contains JSON, it\ncan be used with a ``then()`` callback chain.\n\n.. code-block:: javascript\n\n const room_url = {{ url_for(\"room_detail\", id=room.id)|tojson }}\n fetch(room_url)\n .then(response => response.json())\n .then(data => {\n // data is a parsed JSON object\n })\n\nTo send data, use a data method such as POST, and pass the ``body``\noption. The most common types for data are form data or JSON data.\n\nTo send form data, pass a populated |FormData|_ object. This uses the\nsame format as an HTML form, and would be accessed with ``request.form``\nin a Flask view.\n\n.. code-block:: javascript\n\n let data = new FormData()\n data.append(\"name\": \"Flask Room\")\n data.append(\"description\": \"Talk about Flask here.\")\n fetch(room_url, {\n \"method\": \"POST\",\n \"body\": data,\n }).then(...)\n\nIn general, prefer sending request data as form data, as would be used\nwhen submitting an HTML form. JSON can represent more complex data, but\nunless you need that it's better to stick with the simpler format. When\nsending JSON data, the ``Content-Type: application/json`` header must be\nsent as well, otherwise Flask will return a 400 error.\n\n.. code-block:: javascript\n\n let data = {\n \"name\": \"Flask Room\",\n \"description\": \"Talk about Flask here.\",\n }\n fetch(room_url, {\n \"method\": \"POST\",\n \"headers\": {\"Content-Type\": \"application/json\"},\n \"body\": JSON.stringify(data),\n }).then(...)\n\n.. |Promise| replace:: ``Promise``\n.. _Promise: https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/Promise\n.. |FormData| replace:: ``FormData``\n.. _FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData\n\n\nFollowing Redirects\n-------------------\n\nA response might be a redirect, for example if you logged in with\nJavaScript instead of a traditional HTML form, and your view returned\na redirect instead of JSON. JavaScript requests do follow redirects, but\nthey don't change the page. If you want to make the page change you can\ninspect the response and apply the redirect manually.\n\n.. code-block:: javascript\n\n fetch(\"/login\", {\"body\": ...}).then(\n response => {\n if (response.redirected) {\n window.location = response.url\n } else {\n showLoginError()\n }\n }\n )\n\n\nReplacing Content\n-----------------\n\nA response might be new HTML, either a new section of the page to add or\nreplace, or an entirely new page. In general, if you're returning the\nentire page, it would be better to handle that with a redirect as shown\nin the previous section. The following example shows how to replace a\n``
`` with the HTML returned by a request.\n\n.. code-block:: html\n\n
\n {{ include \"geology_fact.html\" }}\n
\n \n\n\nReturn JSON from Views\n----------------------\n\nTo return a JSON object from your API view, you can directly return a\ndict from the view. It will be serialized to JSON automatically.\n\n.. code-block:: python\n\n @app.route(\"/user/\")\n def user_detail(id):\n user = User.query.get_or_404(id)\n return {\n \"username\": User.username,\n \"email\": User.email,\n \"picture\": url_for(\"static\", filename=f\"users/{id}/profile.png\"),\n }\n\nIf you want to return another JSON type, use the\n:func:`~flask.json.jsonify` function, which creates a response object\nwith the given data serialized to JSON.\n\n.. code-block:: python\n\n from flask import jsonify\n\n @app.route(\"/users\")\n def user_list():\n users = User.query.order_by(User.name).all()\n return jsonify([u.to_json() for u in users])\n\nIt is usually not a good idea to return file data in a JSON response.\nJSON cannot represent binary data directly, so it must be base64\nencoded, which can be slow, takes more bandwidth to send, and is not as\neasy to cache. Instead, serve files using one view, and generate a URL\nto the desired file to include in the JSON. Then the client can make a\nseparate request to get the linked resource after getting the JSON.\n\n\nReceiving JSON in Views\n-----------------------\n\nUse the :attr:`~flask.Request.json` property of the\n:data:`~flask.request` object to decode the request's body as JSON. If\nthe body is not valid JSON, or the ``Content-Type`` header is not set to\n``application/json``, a 400 Bad Request error will be raised.\n\n.. code-block:: python\n\n from flask import request\n\n @app.post(\"/user/\")\n def user_update(id):\n user = User.query.get_or_404(id)\n user.update_from_json(request.json)\n db.session.commit()\n return user.to_json()\n"},{"id":63,"name":"tests/test_apps/blueprintapp/apps/admin","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/blueprintapp/apps/admin","id":64,"nodeType":"File","text":"from flask import Blueprint\nfrom flask import render_template\n\nadmin = Blueprint(\n \"admin\",\n __name__,\n url_prefix=\"/admin\",\n template_folder=\"templates\",\n static_folder=\"static\",\n)\n\n\n@admin.route(\"/\")\ndef index():\n return render_template(\"admin/index.html\")\n\n\n@admin.route(\"/index2\")\ndef index2():\n return render_template(\"./admin/index.html\")\n"},{"id":65,"name":"tests/test_apps/cliapp","nodeType":"Package"},{"fileName":"factory.py","filePath":"tests/test_apps/cliapp","id":66,"nodeType":"File","text":"from flask import Flask\n\n\ndef create_app():\n return Flask(\"app\")\n\n\ndef create_app2(foo, bar):\n return Flask(\"_\".join([\"app2\", foo, bar]))\n\n\ndef no_app():\n pass\n"},{"id":67,"name":"examples/javascript/js_example/templates","nodeType":"Package"},{"id":68,"name":"jquery.html","nodeType":"TextFile","path":"examples/javascript/js_example/templates","text":"{% extends 'base.html' %}\n\n{% block intro %}\n jQuery is a popular library that\n adds cross browser APIs for common tasks. However, it requires loading\n an extra library.\n{% endblock %}\n\n{% block script %}\n \n \n{% endblock %}\n"},{"id":69,"name":"mail.txt","nodeType":"TextFile","path":"tests/templates","text":"{{ foo}} Mail\n"},{"id":70,"name":"template_test.html","nodeType":"TextFile","path":"tests/templates","text":"{% if value is boolean %}\n Success!\n{% endif %}\n"},{"id":71,"name":"examples/tutorial/flaskr/templates","nodeType":"Package"},{"id":72,"name":"base.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates","text":"\n{% block title %}{% endblock %} - Flaskr\n\n\n
\n
\n {% block header %}{% endblock %}\n
\n {% for message in get_flashed_messages() %}\n
{{ message }}
\n {% endfor %}\n {% block content %}{% endblock %}\n
\n"},{"id":73,"name":"logo-lineart.svg","nodeType":"TextFile","path":"artwork","text":"\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n image/svg+xml\n \n \n \n \n \n \n \n \n \n \n\n"},{"id":74,"name":"examples/tutorial/tests","nodeType":"Package"},{"id":75,"name":"data.sql","nodeType":"TextFile","path":"examples/tutorial/tests","text":"INSERT INTO user (username, password)\nVALUES\n ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),\n ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');\n\nINSERT INTO post (title, body, author_id, created)\nVALUES\n ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');\n"},{"fileName":"typing_route.py","filePath":"tests/typing","id":76,"nodeType":"File","text":"from __future__ import annotations\n\nimport typing as t\nfrom http import HTTPStatus\n\nimport typing_extensions as te\n\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask import stream_template\nfrom flask.templating import render_template\nfrom flask.views import View\nfrom flask.wrappers import Response\n\napp = Flask(__name__)\n\n\n@app.route(\"/str\")\ndef hello_str() -> str:\n return \"

Hello, World!

\"\n\n\n@app.route(\"/bytes\")\ndef hello_bytes() -> bytes:\n return b\"

Hello, World!

\"\n\n\n@app.route(\"/json\")\ndef hello_json() -> Response:\n return jsonify(\"Hello, World!\")\n\n\n@app.route(\"/json/dict\")\ndef hello_json_dict() -> t.Dict[str, t.Any]:\n return {\"response\": \"Hello, World!\"}\n\n\n@app.route(\"/json/dict\")\ndef hello_json_list() -> t.List[t.Any]:\n return [{\"message\": \"Hello\"}, {\"message\": \"World\"}]\n\n\nclass StatusJSON(te.TypedDict):\n status: str\n\n\n@app.route(\"/typed-dict\")\ndef typed_dict() -> StatusJSON:\n return {\"status\": \"ok\"}\n\n\n@app.route(\"/generator\")\ndef hello_generator() -> t.Generator[str, None, None]:\n def show() -> t.Generator[str, None, None]:\n for x in range(100):\n yield f\"data:{x}\\n\\n\"\n\n return show()\n\n\n@app.route(\"/generator-expression\")\ndef hello_generator_expression() -> t.Iterator[bytes]:\n return (f\"data:{x}\\n\\n\".encode() for x in range(100))\n\n\n@app.route(\"/iterator\")\ndef hello_iterator() -> t.Iterator[str]:\n return iter([f\"data:{x}\\n\\n\" for x in range(100)])\n\n\n@app.route(\"/status\")\n@app.route(\"/status/\")\ndef tuple_status(code: int = 200) -> tuple[str, int]:\n return \"hello\", code\n\n\n@app.route(\"/status-enum\")\ndef tuple_status_enum() -> tuple[str, int]:\n return \"hello\", HTTPStatus.OK\n\n\n@app.route(\"/headers\")\ndef tuple_headers() -> tuple[str, dict[str, str]]:\n return \"Hello, World!\", {\"Content-Type\": \"text/plain\"}\n\n\n@app.route(\"/template\")\n@app.route(\"/template/\")\ndef return_template(name: str | None = None) -> str:\n return render_template(\"index.html\", name=name)\n\n\n@app.route(\"/template\")\ndef return_template_stream() -> t.Iterator[str]:\n return stream_template(\"index.html\", name=\"Hello\")\n\n\n@app.route(\"/async\")\nasync def async_route() -> str:\n return \"Hello\"\n\n\nclass RenderTemplateView(View):\n def __init__(self: RenderTemplateView, template_name: str) -> None:\n self.template_name = template_name\n\n def dispatch_request(self: RenderTemplateView) -> str:\n return render_template(self.template_name)\n\n\napp.add_url_rule(\n \"/about\",\n view_func=RenderTemplateView.as_view(\"about_page\", template_name=\"about.html\"),\n)\n"},{"id":77,"name":".github/workflows","nodeType":"Package"},{"id":78,"name":"tests.yaml","nodeType":"TextFile","path":".github/workflows","text":"name: Tests\non:\n push:\n branches:\n - main\n - '*.x'\n paths-ignore:\n - 'docs/**'\n - '*.md'\n - '*.rst'\n pull_request:\n branches:\n - main\n - '*.x'\n paths-ignore:\n - 'docs/**'\n - '*.md'\n - '*.rst'\njobs:\n tests:\n name: ${{ matrix.name }}\n runs-on: ${{ matrix.os }}\n strategy:\n fail-fast: false\n matrix:\n include:\n - {name: Linux, python: '3.11', os: ubuntu-latest, tox: py311}\n - {name: Windows, python: '3.11', os: windows-latest, tox: py311}\n - {name: Mac, python: '3.11', os: macos-latest, tox: py311}\n - {name: '3.12-dev', python: '3.12-dev', os: ubuntu-latest, tox: py312}\n - {name: '3.10', python: '3.10', os: ubuntu-latest, tox: py310}\n - {name: '3.9', python: '3.9', os: ubuntu-latest, tox: py39}\n - {name: '3.8', python: '3.8', os: ubuntu-latest, tox: py38}\n - {name: '3.7', python: '3.7', os: ubuntu-latest, tox: py37}\n - {name: 'PyPy', python: 'pypy-3.9', os: ubuntu-latest, tox: pypy39}\n - {name: 'Pallets Minimum Versions', python: '3.11', os: ubuntu-latest, tox: py311-min}\n - {name: 'Pallets Development Versions', python: '3.7', os: ubuntu-latest, tox: py37-dev}\n - {name: Typing, python: '3.11', os: ubuntu-latest, tox: typing}\n steps:\n - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3\n - uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435\n with:\n python-version: ${{ matrix.python }}\n cache: 'pip'\n cache-dependency-path: 'requirements/*.txt'\n - name: update pip\n run: |\n pip install -U wheel\n pip install -U setuptools\n python -m pip install -U pip\n - name: cache mypy\n uses: actions/cache@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c8\n with:\n path: ./.mypy_cache\n key: mypy|${{ matrix.python }}|${{ hashFiles('pyproject.toml') }}\n if: matrix.tox == 'typing'\n - run: pip install tox\n - run: tox run -e ${{ matrix.tox }}\n"},{"id":79,"name":"message.txt","nodeType":"TextFile","path":"tests/test_apps/cliapp","text":"So long, and thanks for all the fish.\n"},{"id":80,"name":"license.rst","nodeType":"TextFile","path":"docs","text":"License\n=======\n\nBSD-3-Clause Source License\n---------------------------\n\nThe BSD-3-Clause license applies to all files in the Flask repository\nand source distribution. This includes Flask's source code, the\nexamples, and tests, as well as the documentation.\n\n.. include:: ../LICENSE.rst\n\n\nArtwork License\n---------------\n\nThis license applies to Flask's logo.\n\n.. include:: ../artwork/LICENSE.rst\n"},{"id":81,"name":".github","nodeType":"Package"},{"id":82,"name":"SECURITY.md","nodeType":"TextFile","path":".github","text":"# Security Policy\n\nIf you believe you have identified a security issue with a Pallets\nproject, **do not open a public issue**. To responsibly report a\nsecurity issue, please email security@palletsprojects.com. A security\nteam member will contact you acknowledging the report and how to\ncontinue.\n\nBe sure to include as much detail as necessary in your report. As with\nreporting normal issues, a minimal reproducible example will help the\nmaintainers address the issue faster. If you are able, you may also\ninclude a fix for the issue generated with `git format-patch`.\n\nThe current and previous release will receive security patches, with\nolder versions evaluated based on usage information and severity.\n\nAfter fixing an issue, we will make a security release along with an\nannouncement on our blog. We may obtain a CVE id as well. You may\ninclude a name and link if you would like to be credited for the report.\n"},{"id":83,"name":"viewdecorators.rst","nodeType":"TextFile","path":"docs/patterns","text":"View Decorators\n===============\n\nPython has a really interesting feature called function decorators. This\nallows some really neat things for web applications. Because each view in\nFlask is a function, decorators can be used to inject additional\nfunctionality to one or more functions. The :meth:`~flask.Flask.route`\ndecorator is the one you probably used already. But there are use cases\nfor implementing your own decorator. For instance, imagine you have a\nview that should only be used by people that are logged in. If a user\ngoes to the site and is not logged in, they should be redirected to the\nlogin page. This is a good example of a use case where a decorator is an\nexcellent solution.\n\nLogin Required Decorator\n------------------------\n\nSo let's implement such a decorator. A decorator is a function that\nwraps and replaces another function. Since the original function is\nreplaced, you need to remember to copy the original function's information\nto the new function. Use :func:`functools.wraps` to handle this for you.\n\nThis example assumes that the login page is called ``'login'`` and that\nthe current user is stored in ``g.user`` and is ``None`` if there is no-one\nlogged in. ::\n\n from functools import wraps\n from flask import g, request, redirect, url_for\n\n def login_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if g.user is None:\n return redirect(url_for('login', next=request.url))\n return f(*args, **kwargs)\n return decorated_function\n\nTo use the decorator, apply it as innermost decorator to a view function.\nWhen applying further decorators, always remember\nthat the :meth:`~flask.Flask.route` decorator is the outermost. ::\n\n @app.route('/secret_page')\n @login_required\n def secret_page():\n pass\n\n.. note::\n The ``next`` value will exist in ``request.args`` after a ``GET`` request for\n the login page. You'll have to pass it along when sending the ``POST`` request\n from the login form. You can do this with a hidden input tag, then retrieve it\n from ``request.form`` when logging the user in. ::\n\n \n\n\nCaching Decorator\n-----------------\n\nImagine you have a view function that does an expensive calculation and\nbecause of that you would like to cache the generated results for a\ncertain amount of time. A decorator would be nice for that. We're\nassuming you have set up a cache like mentioned in :doc:`caching`.\n\nHere is an example cache function. It generates the cache key from a\nspecific prefix (actually a format string) and the current path of the\nrequest. Notice that we are using a function that first creates the\ndecorator that then decorates the function. Sounds awful? Unfortunately\nit is a little bit more complex, but the code should still be\nstraightforward to read.\n\nThe decorated function will then work as follows\n\n1. get the unique cache key for the current request based on the current\n path.\n2. get the value for that key from the cache. If the cache returned\n something we will return that value.\n3. otherwise the original function is called and the return value is\n stored in the cache for the timeout provided (by default 5 minutes).\n\nHere the code::\n\n from functools import wraps\n from flask import request\n\n def cached(timeout=5 * 60, key='view/{}'):\n def decorator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n cache_key = key.format(request.path)\n rv = cache.get(cache_key)\n if rv is not None:\n return rv\n rv = f(*args, **kwargs)\n cache.set(cache_key, rv, timeout=timeout)\n return rv\n return decorated_function\n return decorator\n\nNotice that this assumes an instantiated ``cache`` object is available, see\n:doc:`caching`.\n\n\nTemplating Decorator\n--------------------\n\nA common pattern invented by the TurboGears guys a while back is a\ntemplating decorator. The idea of that decorator is that you return a\ndictionary with the values passed to the template from the view function\nand the template is automatically rendered. With that, the following\nthree examples do exactly the same::\n\n @app.route('/')\n def index():\n return render_template('index.html', value=42)\n\n @app.route('/')\n @templated('index.html')\n def index():\n return dict(value=42)\n\n @app.route('/')\n @templated()\n def index():\n return dict(value=42)\n\nAs you can see, if no template name is provided it will use the endpoint\nof the URL map with dots converted to slashes + ``'.html'``. Otherwise\nthe provided template name is used. When the decorated function returns,\nthe dictionary returned is passed to the template rendering function. If\n``None`` is returned, an empty dictionary is assumed, if something else than\na dictionary is returned we return it from the function unchanged. That\nway you can still use the redirect function or return simple strings.\n\nHere is the code for that decorator::\n\n from functools import wraps\n from flask import request, render_template\n\n def templated(template=None):\n def decorator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n template_name = template\n if template_name is None:\n template_name = f\"{request.endpoint.replace('.', '/')}.html\"\n ctx = f(*args, **kwargs)\n if ctx is None:\n ctx = {}\n elif not isinstance(ctx, dict):\n return ctx\n return render_template(template_name, **ctx)\n return decorated_function\n return decorator\n\n\nEndpoint Decorator\n------------------\n\nWhen you want to use the werkzeug routing system for more flexibility you\nneed to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`\nto a view function. This is possible with this decorator. For example::\n\n from flask import Flask\n from werkzeug.routing import Rule\n\n app = Flask(__name__)\n app.url_map.add(Rule('/', endpoint='index'))\n\n @app.endpoint('index')\n def my_index():\n return \"Hello world\"\n"},{"id":84,"name":"login.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates/auth","text":"{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}Log In{% endblock %}

\n{% endblock %}\n\n{% block content %}\n \n \n \n \n \n \n \n{% endblock %}\n"},{"id":85,"name":".pre-commit-config.yaml","nodeType":"TextFile","path":"","text":"ci:\n autoupdate_branch: \"2.2.x\"\n autoupdate_schedule: monthly\nrepos:\n - repo: https://github.com/asottile/pyupgrade\n rev: v3.3.1\n hooks:\n - id: pyupgrade\n args: [\"--py37-plus\"]\n - repo: https://github.com/asottile/reorder_python_imports\n rev: v3.9.0\n hooks:\n - id: reorder-python-imports\n name: Reorder Python imports (src, tests)\n files: \"^(?!examples/)\"\n args: [\"--application-directories\", \"src\"]\n - repo: https://github.com/psf/black\n rev: 23.3.0\n hooks:\n - id: black\n - repo: https://github.com/PyCQA/flake8\n rev: 6.0.0\n hooks:\n - id: flake8\n additional_dependencies:\n - flake8-bugbear\n - flake8-implicit-str-concat\n - repo: https://github.com/peterdemin/pip-compile-multi\n rev: v2.6.2\n hooks:\n - id: pip-compile-multi-verify\n - repo: https://github.com/pre-commit/pre-commit-hooks\n rev: v4.4.0\n hooks:\n - id: fix-byte-order-marker\n - id: trailing-whitespace\n - id: end-of-file-fixer\n"},{"id":86,"name":"logo-full.svg","nodeType":"TextFile","path":"artwork","text":"\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n image/svg+xml\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"},{"id":87,"name":"src/flask","nodeType":"Package"},{"fileName":"views.py","filePath":"src/flask","id":88,"nodeType":"File","text":"import typing as t\n\nfrom . import typing as ft\nfrom .globals import current_app\nfrom .globals import request\n\n\nhttp_method_funcs = frozenset(\n [\"get\", \"post\", \"head\", \"options\", \"delete\", \"put\", \"trace\", \"patch\"]\n)\n\n\nclass View:\n \"\"\"Subclass this class and override :meth:`dispatch_request` to\n create a generic class-based view. Call :meth:`as_view` to create a\n view function that creates an instance of the class with the given\n arguments and calls its ``dispatch_request`` method with any URL\n variables.\n\n See :doc:`views` for a detailed guide.\n\n .. code-block:: python\n\n class Hello(View):\n init_every_request = False\n\n def dispatch_request(self, name):\n return f\"Hello, {name}!\"\n\n app.add_url_rule(\n \"/hello/\", view_func=Hello.as_view(\"hello\")\n )\n\n Set :attr:`methods` on the class to change what methods the view\n accepts.\n\n Set :attr:`decorators` on the class to apply a list of decorators to\n the generated view function. Decorators applied to the class itself\n will not be applied to the generated view function!\n\n Set :attr:`init_every_request` to ``False`` for efficiency, unless\n you need to store request-global data on ``self``.\n \"\"\"\n\n #: The methods this view is registered for. Uses the same default\n #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n #: ``add_url_rule`` by default.\n methods: t.ClassVar[t.Optional[t.Collection[str]]] = None\n\n #: Control whether the ``OPTIONS`` method is handled automatically.\n #: Uses the same default (``True``) as ``route`` and\n #: ``add_url_rule`` by default.\n provide_automatic_options: t.ClassVar[t.Optional[bool]] = None\n\n #: A list of decorators to apply, in order, to the generated view\n #: function. Remember that ``@decorator`` syntax is applied bottom\n #: to top, so the first decorator in the list would be the bottom\n #: decorator.\n #:\n #: .. versionadded:: 0.8\n decorators: t.ClassVar[t.List[t.Callable]] = []\n\n #: Create a new instance of this view class for every request by\n #: default. If a view subclass sets this to ``False``, the same\n #: instance is used for every request.\n #:\n #: A single instance is more efficient, especially if complex setup\n #: is done during init. However, storing data on ``self`` is no\n #: longer safe across requests, and :data:`~flask.g` should be used\n #: instead.\n #:\n #: .. versionadded:: 2.2\n init_every_request: t.ClassVar[bool] = True\n\n def dispatch_request(self) -> ft.ResponseReturnValue:\n \"\"\"The actual view function behavior. Subclasses must override\n this and return a valid response. Any variables from the URL\n rule are passed as keyword arguments.\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> ft.RouteCallable:\n \"\"\"Convert the class into a view function that can be registered\n for a route.\n\n By default, the generated view will create a new instance of the\n view class for every request and call its\n :meth:`dispatch_request` method. If the view class sets\n :attr:`init_every_request` to ``False``, the same instance will\n be used for every request.\n\n Except for ``name``, all other arguments passed to this method\n are forwarded to the view class ``__init__`` method.\n\n .. versionchanged:: 2.2\n Added the ``init_every_request`` class attribute.\n \"\"\"\n if cls.init_every_request:\n\n def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n self = view.view_class( # type: ignore[attr-defined]\n *class_args, **class_kwargs\n )\n return current_app.ensure_sync(self.dispatch_request)(**kwargs)\n\n else:\n self = cls(*class_args, **class_kwargs)\n\n def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n return current_app.ensure_sync(self.dispatch_request)(**kwargs)\n\n if cls.decorators:\n view.__name__ = name\n view.__module__ = cls.__module__\n for decorator in cls.decorators:\n view = decorator(view)\n\n # We attach the view class to the view function for two reasons:\n # first of all it allows us to easily figure out what class-based\n # view this thing came from, secondly it's also used for instantiating\n # the view class so you can actually replace it with something else\n # for testing purposes and debugging.\n view.view_class = cls # type: ignore\n view.__name__ = name\n view.__doc__ = cls.__doc__\n view.__module__ = cls.__module__\n view.methods = cls.methods # type: ignore\n view.provide_automatic_options = cls.provide_automatic_options # type: ignore\n return view\n\n\nclass MethodView(View):\n \"\"\"Dispatches request methods to the corresponding instance methods.\n For example, if you implement a ``get`` method, it will be used to\n handle ``GET`` requests.\n\n This can be useful for defining a REST API.\n\n :attr:`methods` is automatically set based on the methods defined on\n the class.\n\n See :doc:`views` for a detailed guide.\n\n .. code-block:: python\n\n class CounterAPI(MethodView):\n def get(self):\n return str(session.get(\"counter\", 0))\n\n def post(self):\n session[\"counter\"] = session.get(\"counter\", 0) + 1\n return redirect(url_for(\"counter\"))\n\n app.add_url_rule(\n \"/counter\", view_func=CounterAPI.as_view(\"counter\")\n )\n \"\"\"\n\n def __init_subclass__(cls, **kwargs: t.Any) -> None:\n super().__init_subclass__(**kwargs)\n\n if \"methods\" not in cls.__dict__:\n methods = set()\n\n for base in cls.__bases__:\n if getattr(base, \"methods\", None):\n methods.update(base.methods) # type: ignore[attr-defined]\n\n for key in http_method_funcs:\n if hasattr(cls, key):\n methods.add(key.upper())\n\n if methods:\n cls.methods = methods\n\n def dispatch_request(self, **kwargs: t.Any) -> ft.ResponseReturnValue:\n meth = getattr(self, request.method.lower(), None)\n\n # If the request method is HEAD and we don't have a handler for it\n # retry with GET.\n if meth is None and request.method == \"HEAD\":\n meth = getattr(self, \"get\", None)\n\n assert meth is not None, f\"Unimplemented method {request.method!r}\"\n return current_app.ensure_sync(meth)(**kwargs)\n"},{"id":89,"name":".devcontainer","nodeType":"Package"},{"id":90,"name":"devcontainer.json","nodeType":"TextFile","path":".devcontainer","text":"{\n \"name\": \"pallets/flask\",\n \"image\": \"mcr.microsoft.com/devcontainers/python:3\",\n \"customizations\": {\n \"vscode\": {\n \"settings\": {\n \"python.defaultInterpreterPath\": \"${workspaceFolder}/.venv\",\n \"python.terminal.activateEnvInCurrentTerminal\": true,\n \"python.terminal.launchArgs\": [\n \"-X\",\n \"dev\"\n ]\n }\n }\n },\n \"onCreateCommand\": \".devcontainer/on-create-command.sh\"\n}\n"},{"attributeType":"Flask","col":0,"comment":"null","endLoc":46,"id":91,"name":"current_app","nodeType":"Attribute","startLoc":46,"text":"current_app"},{"id":92,"name":".github/ISSUE_TEMPLATE","nodeType":"Package"},{"id":93,"name":"feature-request.md","nodeType":"TextFile","path":".github/ISSUE_TEMPLATE","text":"---\nname: Feature request\nabout: Suggest a new feature for Flask\n---\n\n\n\n\n"},{"id":94,"name":"favicon.rst","nodeType":"TextFile","path":"docs/patterns","text":"Adding a favicon\n================\n\nA \"favicon\" is an icon used by browsers for tabs and bookmarks. This helps\nto distinguish your website and to give it a unique brand.\n\nA common question is how to add a favicon to a Flask application. First, of\ncourse, you need an icon. It should be 16 × 16 pixels and in the ICO file\nformat. This is not a requirement but a de-facto standard supported by all\nrelevant browsers. Put the icon in your static directory as\n:file:`favicon.ico`.\n\nNow, to get browsers to find your icon, the correct way is to add a link\ntag in your HTML. So, for example:\n\n.. sourcecode:: html+jinja\n\n \n\nThat's all you need for most browsers, however some really old ones do not\nsupport this standard. The old de-facto standard is to serve this file,\nwith this name, at the website root. If your application is not mounted at\nthe root path of the domain you either need to configure the web server to\nserve the icon at the root or if you can't do that you're out of luck. If\nhowever your application is the root you can simply route a redirect::\n\n app.add_url_rule('/favicon.ico',\n redirect_to=url_for('static', filename='favicon.ico'))\n\nIf you want to save the extra redirect request you can also write a view\nusing :func:`~flask.send_from_directory`::\n\n import os\n from flask import send_from_directory\n\n @app.route('/favicon.ico')\n def favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),\n 'favicon.ico', mimetype='image/vnd.microsoft.icon')\n\nWe can leave out the explicit mimetype and it will be guessed, but we may\nas well specify it to avoid the extra guessing, as it will always be the\nsame.\n\nThe above will serve the icon via your application and if possible it's\nbetter to configure your dedicated web server to serve it; refer to the\nweb server's documentation.\n\nSee also\n--------\n\n* The `Favicon `_ article on\n Wikipedia\n"},{"id":95,"name":"fileuploads.rst","nodeType":"TextFile","path":"docs/patterns","text":"Uploading Files\n===============\n\nAh yes, the good old problem of file uploads. The basic idea of file\nuploads is actually quite simple. It basically works like this:\n\n1. A ``
`` tag is marked with ``enctype=multipart/form-data``\n and an ```` is placed in that form.\n2. The application accesses the file from the :attr:`~flask.request.files`\n dictionary on the request object.\n3. use the :meth:`~werkzeug.datastructures.FileStorage.save` method of the file to save\n the file permanently somewhere on the filesystem.\n\nA Gentle Introduction\n---------------------\n\nLet's start with a very basic application that uploads a file to a\nspecific upload folder and displays a file to the user. Let's look at the\nbootstrapping code for our application::\n\n import os\n from flask import Flask, flash, request, redirect, url_for\n from werkzeug.utils import secure_filename\n\n UPLOAD_FOLDER = '/path/to/the/uploads'\n ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}\n\n app = Flask(__name__)\n app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\nSo first we need a couple of imports. Most should be straightforward, the\n:func:`werkzeug.secure_filename` is explained a little bit later. The\n``UPLOAD_FOLDER`` is where we will store the uploaded files and the\n``ALLOWED_EXTENSIONS`` is the set of allowed file extensions.\n\nWhy do we limit the extensions that are allowed? You probably don't want\nyour users to be able to upload everything there if the server is directly\nsending out the data to the client. That way you can make sure that users\nare not able to upload HTML files that would cause XSS problems (see\n:ref:`security-xss`). Also make sure to disallow ``.php`` files if the server\nexecutes them, but who has PHP installed on their server, right? :)\n\nNext the functions that check if an extension is valid and that uploads\nthe file and redirects the user to the URL for the uploaded file::\n\n def allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n @app.route('/', methods=['GET', 'POST'])\n def upload_file():\n if request.method == 'POST':\n # check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['file']\n # If the user does not select a file, the browser submits an\n # empty file without a filename.\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return redirect(url_for('download_file', name=filename))\n return '''\n \n Upload new File\n

Upload new File

\n \n \n \n
\n '''\n\nSo what does that :func:`~werkzeug.utils.secure_filename` function actually do?\nNow the problem is that there is that principle called \"never trust user\ninput\". This is also true for the filename of an uploaded file. All\nsubmitted form data can be forged, and filenames can be dangerous. For\nthe moment just remember: always use that function to secure a filename\nbefore storing it directly on the filesystem.\n\n.. admonition:: Information for the Pros\n\n So you're interested in what that :func:`~werkzeug.utils.secure_filename`\n function does and what the problem is if you're not using it? So just\n imagine someone would send the following information as `filename` to\n your application::\n\n filename = \"../../../../home/username/.bashrc\"\n\n Assuming the number of ``../`` is correct and you would join this with\n the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on\n the server's filesystem he or she should not modify. This does require some\n knowledge about how the application looks like, but trust me, hackers\n are patient :)\n\n Now let's look how that function works:\n\n >>> secure_filename('../../../../home/username/.bashrc')\n 'home_username_.bashrc'\n\nWe want to be able to serve the uploaded files so they can be downloaded\nby users. We'll define a ``download_file`` view to serve files in the\nupload folder by name. ``url_for(\"download_file\", name=name)`` generates\ndownload URLs.\n\n.. code-block:: python\n\n from flask import send_from_directory\n\n @app.route('/uploads/')\n def download_file(name):\n return send_from_directory(app.config[\"UPLOAD_FOLDER\"], name)\n\nIf you're using middleware or the HTTP server to serve files, you can\nregister the ``download_file`` endpoint as ``build_only`` so ``url_for``\nwill work without a view function.\n\n.. code-block:: python\n\n app.add_url_rule(\n \"/uploads/\", endpoint=\"download_file\", build_only=True\n )\n\n\nImproving Uploads\n-----------------\n\n.. versionadded:: 0.6\n\nSo how exactly does Flask handle uploads? Well it will store them in the\nwebserver's memory if the files are reasonably small, otherwise in a\ntemporary location (as returned by :func:`tempfile.gettempdir`). But how\ndo you specify the maximum file size after which an upload is aborted? By\ndefault Flask will happily accept file uploads with an unlimited amount of\nmemory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``\nconfig key::\n\n from flask import Flask, Request\n\n app = Flask(__name__)\n app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000\n\nThe code above will limit the maximum allowed payload to 16 megabytes.\nIf a larger file is transmitted, Flask will raise a\n:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.\n\n.. admonition:: Connection Reset Issue\n\n When using the local development server, you may get a connection\n reset error instead of a 413 response. You will get the correct\n status response when running the app with a production WSGI server.\n\nThis feature was added in Flask 0.6 but can be achieved in older versions\nas well by subclassing the request object. For more information on that\nconsult the Werkzeug documentation on file handling.\n\n\nUpload Progress Bars\n--------------------\n\nA while ago many developers had the idea to read the incoming file in\nsmall chunks and store the upload progress in the database to be able to\npoll the progress with JavaScript from the client. The client asks the\nserver every 5 seconds how much it has transmitted, but this is\nsomething it should already know.\n\nAn Easier Solution\n------------------\n\nNow there are better solutions that work faster and are more reliable. There\nare JavaScript libraries like jQuery_ that have form plugins to ease the\nconstruction of progress bar.\n\nBecause the common pattern for file uploads exists almost unchanged in all\napplications dealing with uploads, there are also some Flask extensions that\nimplement a full fledged upload mechanism that allows controlling which\nfile extensions are allowed to be uploaded.\n\n.. _jQuery: https://jquery.com/\n"},{"fileName":"conftest.py","filePath":"examples/tutorial/tests","id":96,"nodeType":"File","text":"import os\nimport tempfile\n\nimport pytest\n\nfrom flaskr import create_app\nfrom flaskr.db import get_db\nfrom flaskr.db import init_db\n\n# read in SQL for populating test data\nwith open(os.path.join(os.path.dirname(__file__), \"data.sql\"), \"rb\") as f:\n _data_sql = f.read().decode(\"utf8\")\n\n\n@pytest.fixture\ndef app():\n \"\"\"Create and configure a new app instance for each test.\"\"\"\n # create a temporary file to isolate the database for each test\n db_fd, db_path = tempfile.mkstemp()\n # create the app with common test config\n app = create_app({\"TESTING\": True, \"DATABASE\": db_path})\n\n # create the database and load test data\n with app.app_context():\n init_db()\n get_db().executescript(_data_sql)\n\n yield app\n\n # close and remove the temporary database\n os.close(db_fd)\n os.unlink(db_path)\n\n\n@pytest.fixture\ndef client(app):\n \"\"\"A test client for the app.\"\"\"\n return app.test_client()\n\n\n@pytest.fixture\ndef runner(app):\n \"\"\"A test runner for the app's Click commands.\"\"\"\n return app.test_cli_runner()\n\n\nclass AuthActions:\n def __init__(self, client):\n self._client = client\n\n def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )\n\n def logout(self):\n return self._client.get(\"/auth/logout\")\n\n\n@pytest.fixture\ndef auth(client):\n return AuthActions(client)\n"},{"id":97,"name":"shell.rst","nodeType":"TextFile","path":"docs","text":"Working with the Shell\n======================\n\n.. versionadded:: 0.3\n\nOne of the reasons everybody loves Python is the interactive shell. It\nbasically allows you to execute Python commands in real time and\nimmediately get results back. Flask itself does not come with an\ninteractive shell, because it does not require any specific setup upfront,\njust import your application and start playing around.\n\nThere are however some handy helpers to make playing around in the shell a\nmore pleasant experience. The main issue with interactive console\nsessions is that you're not triggering a request like a browser does which\nmeans that :data:`~flask.g`, :data:`~flask.request` and others are not\navailable. But the code you want to test might depend on them, so what\ncan you do?\n\nThis is where some helper functions come in handy. Keep in mind however\nthat these functions are not only there for interactive shell usage, but\nalso for unit testing and other situations that require a faked request\ncontext.\n\nGenerally it's recommended that you read :doc:`reqcontext` first.\n\nCommand Line Interface\n----------------------\n\nStarting with Flask 0.11 the recommended way to work with the shell is the\n``flask shell`` command which does a lot of this automatically for you.\nFor instance the shell is automatically initialized with a loaded\napplication context.\n\nFor more information see :doc:`/cli`.\n\nCreating a Request Context\n--------------------------\n\nThe easiest way to create a proper request context from the shell is by\nusing the :attr:`~flask.Flask.test_request_context` method which creates\nus a :class:`~flask.ctx.RequestContext`:\n\n>>> ctx = app.test_request_context()\n\nNormally you would use the ``with`` statement to make this request object\nactive, but in the shell it's easier to use the\n:meth:`~flask.ctx.RequestContext.push` and\n:meth:`~flask.ctx.RequestContext.pop` methods by hand:\n\n>>> ctx.push()\n\nFrom that point onwards you can work with the request object until you\ncall `pop`:\n\n>>> ctx.pop()\n\nFiring Before/After Request\n---------------------------\n\nBy just creating a request context, you still don't have run the code that\nis normally run before a request. This might result in your database\nbeing unavailable if you are connecting to the database in a\nbefore-request callback or the current user not being stored on the\n:data:`~flask.g` object etc.\n\nThis however can easily be done yourself. Just call\n:meth:`~flask.Flask.preprocess_request`:\n\n>>> ctx = app.test_request_context()\n>>> ctx.push()\n>>> app.preprocess_request()\n\nKeep in mind that the :meth:`~flask.Flask.preprocess_request` function\nmight return a response object, in that case just ignore it.\n\nTo shutdown a request, you need to trick a bit before the after request\nfunctions (triggered by :meth:`~flask.Flask.process_response`) operate on\na response object:\n\n>>> app.process_response(app.response_class())\n\n>>> ctx.pop()\n\nThe functions registered as :meth:`~flask.Flask.teardown_request` are\nautomatically called when the context is popped. So this is the perfect\nplace to automatically tear down resources that were needed by the request\ncontext (such as database connections).\n\n\nFurther Improving the Shell Experience\n--------------------------------------\n\nIf you like the idea of experimenting in a shell, create yourself a module\nwith stuff you want to star import into your interactive session. There\nyou could also define some more helper methods for common things such as\ninitializing the database, dropping tables etc.\n\nJust put them into a module (like `shelltools`) and import from there:\n\n>>> from shelltools import *\n"},{"id":98,"name":"requestchecksum.rst","nodeType":"TextFile","path":"docs/patterns","text":"Request Content Checksums\n=========================\n\nVarious pieces of code can consume the request data and preprocess it.\nFor instance JSON data ends up on the request object already read and\nprocessed, form data ends up there as well but goes through a different\ncode path. This seems inconvenient when you want to calculate the\nchecksum of the incoming request data. This is necessary sometimes for\nsome APIs.\n\nFortunately this is however very simple to change by wrapping the input\nstream.\n\nThe following example calculates the SHA1 checksum of the incoming data as\nit gets read and stores it in the WSGI environment::\n\n import hashlib\n\n class ChecksumCalcStream(object):\n\n def __init__(self, stream):\n self._stream = stream\n self._hash = hashlib.sha1()\n\n def read(self, bytes):\n rv = self._stream.read(bytes)\n self._hash.update(rv)\n return rv\n\n def readline(self, size_hint):\n rv = self._stream.readline(size_hint)\n self._hash.update(rv)\n return rv\n\n def generate_checksum(request):\n env = request.environ\n stream = ChecksumCalcStream(env['wsgi.input'])\n env['wsgi.input'] = stream\n return stream._hash\n\nTo use this, all you need to do is to hook the calculating stream in\nbefore the request starts consuming data. (Eg: be careful accessing\n``request.form`` or anything of that nature. ``before_request_handlers``\nfor instance should be careful not to access it).\n\nExample usage::\n\n @app.route('/special-api', methods=['POST'])\n def special_api():\n hash = generate_checksum(request)\n # Accessing this parses the input stream\n files = request.files\n # At this point the hash is fully constructed.\n checksum = hash.hexdigest()\n return f\"Hash was: {checksum}\"\n"},{"id":99,"name":"MANIFEST.in","nodeType":"TextFile","path":"","text":"include CHANGES.rst\ninclude CONTRIBUTING.rst\ninclude tox.ini\ninclude requirements/*.txt\ngraft artwork\ngraft docs\nprune docs/_build\ngraft examples\ngraft tests\ninclude src/flask/py.typed\nglobal-exclude *.pyc\n"},{"id":100,"name":"logging.rst","nodeType":"TextFile","path":"docs","text":"Logging\n=======\n\nFlask uses standard Python :mod:`logging`. Messages about your Flask\napplication are logged with :meth:`app.logger `,\nwhich takes the same name as :attr:`app.name `. This\nlogger can also be used to log your own messages.\n\n.. code-block:: python\n\n @app.route('/login', methods=['POST'])\n def login():\n user = get_user(request.form['username'])\n\n if user.check_password(request.form['password']):\n login_user(user)\n app.logger.info('%s logged in successfully', user.username)\n return redirect(url_for('index'))\n else:\n app.logger.info('%s failed to log in', user.username)\n abort(401)\n\nIf you don't configure logging, Python's default log level is usually\n'warning'. Nothing below the configured level will be visible.\n\n\nBasic Configuration\n-------------------\n\nWhen you want to configure logging for your project, you should do it as soon\nas possible when the program starts. If :meth:`app.logger `\nis accessed before logging is configured, it will add a default handler. If\npossible, configure logging before creating the application object.\n\nThis example uses :func:`~logging.config.dictConfig` to create a logging\nconfiguration similar to Flask's default, except for all logs::\n\n from logging.config import dictConfig\n\n dictConfig({\n 'version': 1,\n 'formatters': {'default': {\n 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',\n }},\n 'handlers': {'wsgi': {\n 'class': 'logging.StreamHandler',\n 'stream': 'ext://flask.logging.wsgi_errors_stream',\n 'formatter': 'default'\n }},\n 'root': {\n 'level': 'INFO',\n 'handlers': ['wsgi']\n }\n })\n\n app = Flask(__name__)\n\n\nDefault Configuration\n`````````````````````\n\nIf you do not configure logging yourself, Flask will add a\n:class:`~logging.StreamHandler` to :meth:`app.logger `\nautomatically. During requests, it will write to the stream specified by the\nWSGI server in ``environ['wsgi.errors']`` (which is usually\n:data:`sys.stderr`). Outside a request, it will log to :data:`sys.stderr`.\n\n\nRemoving the Default Handler\n````````````````````````````\n\nIf you configured logging after accessing\n:meth:`app.logger `, and need to remove the default\nhandler, you can import and remove it::\n\n from flask.logging import default_handler\n\n app.logger.removeHandler(default_handler)\n\n\nEmail Errors to Admins\n----------------------\n\nWhen running the application on a remote server for production, you probably\nwon't be looking at the log messages very often. The WSGI server will probably\nsend log messages to a file, and you'll only check that file if a user tells\nyou something went wrong.\n\nTo be proactive about discovering and fixing bugs, you can configure a\n:class:`logging.handlers.SMTPHandler` to send an email when errors and higher\nare logged. ::\n\n import logging\n from logging.handlers import SMTPHandler\n\n mail_handler = SMTPHandler(\n mailhost='127.0.0.1',\n fromaddr='server-error@example.com',\n toaddrs=['admin@example.com'],\n subject='Application Error'\n )\n mail_handler.setLevel(logging.ERROR)\n mail_handler.setFormatter(logging.Formatter(\n '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'\n ))\n\n if not app.debug:\n app.logger.addHandler(mail_handler)\n\nThis requires that you have an SMTP server set up on the same server. See the\nPython docs for more information about configuring the handler.\n\n\nInjecting Request Information\n-----------------------------\n\nSeeing more information about the request, such as the IP address, may help\ndebugging some errors. You can subclass :class:`logging.Formatter` to inject\nyour own fields that can be used in messages. You can change the formatter for\nFlask's default handler, the mail handler defined above, or any other\nhandler. ::\n\n from flask import has_request_context, request\n from flask.logging import default_handler\n\n class RequestFormatter(logging.Formatter):\n def format(self, record):\n if has_request_context():\n record.url = request.url\n record.remote_addr = request.remote_addr\n else:\n record.url = None\n record.remote_addr = None\n\n return super().format(record)\n\n formatter = RequestFormatter(\n '[%(asctime)s] %(remote_addr)s requested %(url)s\\n'\n '%(levelname)s in %(module)s: %(message)s'\n )\n default_handler.setFormatter(formatter)\n mail_handler.setFormatter(formatter)\n\n\nOther Libraries\n---------------\n\nOther libraries may use logging extensively, and you want to see relevant\nmessages from those logs too. The simplest way to do this is to add handlers\nto the root logger instead of only the app logger. ::\n\n from flask.logging import default_handler\n\n root = logging.getLogger()\n root.addHandler(default_handler)\n root.addHandler(mail_handler)\n\nDepending on your project, it may be more useful to configure each logger you\ncare about separately, instead of configuring only the root logger. ::\n\n for logger in (\n app.logger,\n logging.getLogger('sqlalchemy'),\n logging.getLogger('other_package'),\n ):\n logger.addHandler(default_handler)\n logger.addHandler(mail_handler)\n\n\nWerkzeug\n````````\n\nWerkzeug logs basic request/response information to the ``'werkzeug'`` logger.\nIf the root logger has no handlers configured, Werkzeug adds a\n:class:`~logging.StreamHandler` to its logger.\n\n\nFlask Extensions\n````````````````\n\nDepending on the situation, an extension may choose to log to\n:meth:`app.logger ` or its own named logger. Consult each\nextension's documentation for details.\n"},{"id":101,"name":"examples/celery","nodeType":"Package"},{"id":102,"name":"README.md","nodeType":"TextFile","path":"examples/celery","text":"Background Tasks with Celery\n============================\n\nThis example shows how to configure Celery with Flask, how to set up an API for\nsubmitting tasks and polling results, and how to use that API with JavaScript. See\n[Flask's documentation about Celery](https://flask.palletsprojects.com/patterns/celery/).\n\nFrom this directory, create a virtualenv and install the application into it. Then run a\nCelery worker.\n\n```shell\n$ python3 -m venv .venv\n$ . ./.venv/bin/activate\n$ pip install -r requirements.txt && pip install -e .\n$ celery -A make_celery worker --loglevel INFO\n```\n\nIn a separate terminal, activate the virtualenv and run the Flask development server.\n\n```shell\n$ . ./.venv/bin/activate\n$ flask -A task_app run --debug\n```\n\nGo to http://localhost:5000/ and use the forms to submit tasks. You can see the polling\nrequests in the browser dev tools and the Flask logs. You can see the tasks submitting\nand completing in the Celery logs.\n"},{"id":103,"name":"views.rst","nodeType":"TextFile","path":"docs","text":"Class-based Views\n=================\n\n.. currentmodule:: flask.views\n\nThis page introduces using the :class:`View` and :class:`MethodView`\nclasses to write class-based views.\n\nA class-based view is a class that acts as a view function. Because it\nis a class, different instances of the class can be created with\ndifferent arguments, to change the behavior of the view. This is also\nknown as generic, reusable, or pluggable views.\n\nAn example of where this is useful is defining a class that creates an\nAPI based on the database model it is initialized with.\n\nFor more complex API behavior and customization, look into the various\nAPI extensions for Flask.\n\n\nBasic Reusable View\n-------------------\n\nLet's walk through an example converting a view function to a view\nclass. We start with a view function that queries a list of users then\nrenders a template to show the list.\n\n.. code-block:: python\n\n @app.route(\"/users/\")\n def user_list():\n users = User.query.all()\n return render_template(\"users.html\", users=users)\n\nThis works for the user model, but let's say you also had more models\nthat needed list pages. You'd need to write another view function for\neach model, even though the only thing that would change is the model\nand template name.\n\nInstead, you can write a :class:`View` subclass that will query a model\nand render a template. As the first step, we'll convert the view to a\nclass without any customization.\n\n.. code-block:: python\n\n from flask.views import View\n\n class UserList(View):\n def dispatch_request(self):\n users = User.query.all()\n return render_template(\"users.html\", objects=users)\n\n app.add_url_rule(\"/users/\", view_func=UserList.as_view(\"user_list\"))\n\nThe :meth:`View.dispatch_request` method is the equivalent of the view\nfunction. Calling :meth:`View.as_view` method will create a view\nfunction that can be registered on the app with its\n:meth:`~flask.Flask.add_url_rule` method. The first argument to\n``as_view`` is the name to use to refer to the view with\n:func:`~flask.url_for`.\n\n.. note::\n\n You can't decorate the class with ``@app.route()`` the way you'd\n do with a basic view function.\n\nNext, we need to be able to register the same view class for different\nmodels and templates, to make it more useful than the original function.\nThe class will take two arguments, the model and template, and store\nthem on ``self``. Then ``dispatch_request`` can reference these instead\nof hard-coded values.\n\n.. code-block:: python\n\n class ListView(View):\n def __init__(self, model, template):\n self.model = model\n self.template = template\n\n def dispatch_request(self):\n items = self.model.query.all()\n return render_template(self.template, items=items)\n\nRemember, we create the view function with ``View.as_view()`` instead of\ncreating the class directly. Any extra arguments passed to ``as_view``\nare then passed when creating the class. Now we can register the same\nview to handle multiple models.\n\n.. code-block:: python\n\n app.add_url_rule(\n \"/users/\",\n view_func=ListView.as_view(\"user_list\", User, \"users.html\"),\n )\n app.add_url_rule(\n \"/stories/\",\n view_func=ListView.as_view(\"story_list\", Story, \"stories.html\"),\n )\n\n\nURL Variables\n-------------\n\nAny variables captured by the URL are passed as keyword arguments to the\n``dispatch_request`` method, as they would be for a regular view\nfunction.\n\n.. code-block:: python\n\n class DetailView(View):\n def __init__(self, model):\n self.model = model\n self.template = f\"{model.__name__.lower()}/detail.html\"\n\n def dispatch_request(self, id)\n item = self.model.query.get_or_404(id)\n return render_template(self.template, item=item)\n\n app.add_url_rule(\n \"/users/\",\n view_func=DetailView.as_view(\"user_detail\", User)\n )\n\n\nView Lifetime and ``self``\n--------------------------\n\nBy default, a new instance of the view class is created every time a\nrequest is handled. This means that it is safe to write other data to\n``self`` during the request, since the next request will not see it,\nunlike other forms of global state.\n\nHowever, if your view class needs to do a lot of complex initialization,\ndoing it for every request is unnecessary and can be inefficient. To\navoid this, set :attr:`View.init_every_request` to ``False``, which will\nonly create one instance of the class and use it for every request. In\nthis case, writing to ``self`` is not safe. If you need to store data\nduring the request, use :data:`~flask.g` instead.\n\nIn the ``ListView`` example, nothing writes to ``self`` during the\nrequest, so it is more efficient to create a single instance.\n\n.. code-block:: python\n\n class ListView(View):\n init_every_request = False\n\n def __init__(self, model, template):\n self.model = model\n self.template = template\n\n def dispatch_request(self):\n items = self.model.query.all()\n return render_template(self.template, items=items)\n\nDifferent instances will still be created each for each ``as_view``\ncall, but not for each request to those views.\n\n\nView Decorators\n---------------\n\nThe view class itself is not the view function. View decorators need to\nbe applied to the view function returned by ``as_view``, not the class\nitself. Set :attr:`View.decorators` to a list of decorators to apply.\n\n.. code-block:: python\n\n class UserList(View):\n decorators = [cache(minutes=2), login_required]\n\n app.add_url_rule('/users/', view_func=UserList.as_view())\n\nIf you didn't set ``decorators``, you could apply them manually instead.\nThis is equivalent to:\n\n.. code-block:: python\n\n view = UserList.as_view(\"users_list\")\n view = cache(minutes=2)(view)\n view = login_required(view)\n app.add_url_rule('/users/', view_func=view)\n\nKeep in mind that order matters. If you're used to ``@decorator`` style,\nthis is equivalent to:\n\n.. code-block:: python\n\n @app.route(\"/users/\")\n @login_required\n @cache(minutes=2)\n def user_list():\n ...\n\n\nMethod Hints\n------------\n\nA common pattern is to register a view with ``methods=[\"GET\", \"POST\"]``,\nthen check ``request.method == \"POST\"`` to decide what to do. Setting\n:attr:`View.methods` is equivalent to passing the list of methods to\n``add_url_rule`` or ``route``.\n\n.. code-block:: python\n\n class MyView(View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n if request.method == \"POST\":\n ...\n ...\n\n app.add_url_rule('/my-view', view_func=MyView.as_view('my-view'))\n\nThis is equivalent to the following, except further subclasses can\ninherit or change the methods.\n\n.. code-block:: python\n\n app.add_url_rule(\n \"/my-view\",\n view_func=MyView.as_view(\"my-view\"),\n methods=[\"GET\", \"POST\"],\n )\n\n\nMethod Dispatching and APIs\n---------------------------\n\nFor APIs it can be helpful to use a different function for each HTTP\nmethod. :class:`MethodView` extends the basic :class:`View` to dispatch\nto different methods of the class based on the request method. Each HTTP\nmethod maps to a method of the class with the same (lowercase) name.\n\n:class:`MethodView` automatically sets :attr:`View.methods` based on the\nmethods defined by the class. It even knows how to handle subclasses\nthat override or define other methods.\n\nWe can make a generic ``ItemAPI`` class that provides get (detail),\npatch (edit), and delete methods for a given model. A ``GroupAPI`` can\nprovide get (list) and post (create) methods.\n\n.. code-block:: python\n\n from flask.views import MethodView\n\n class ItemAPI(MethodView):\n init_every_request = False\n\n def __init__(self, model):\n self.model = model\n self.validator = generate_validator(model)\n\n def _get_item(self, id):\n return self.model.query.get_or_404(id)\n\n def get(self, id):\n item = self._get_item(id)\n return jsonify(item.to_json())\n\n def patch(self, id):\n item = self._get_item(id)\n errors = self.validator.validate(item, request.json)\n\n if errors:\n return jsonify(errors), 400\n\n item.update_from_json(request.json)\n db.session.commit()\n return jsonify(item.to_json())\n\n def delete(self, id):\n item = self._get_item(id)\n db.session.delete(item)\n db.session.commit()\n return \"\", 204\n\n class GroupAPI(MethodView):\n init_every_request = False\n\n def __init__(self, model):\n self.model = model\n self.validator = generate_validator(model, create=True)\n\n def get(self):\n items = self.model.query.all()\n return jsonify([item.to_json() for item in items])\n\n def post(self):\n errors = self.validator.validate(request.json)\n\n if errors:\n return jsonify(errors), 400\n\n db.session.add(self.model.from_json(request.json))\n db.session.commit()\n return jsonify(item.to_json())\n\n def register_api(app, model, name):\n item = ItemAPI.as_view(f\"{name}-item\", model)\n group = GroupAPI.as_view(f\"{name}-group\", model)\n app.add_url_rule(f\"/{name}/\", view_func=item)\n app.add_url_rule(f\"/{name}/\", view_func=group)\n\n register_api(app, User, \"users\")\n register_api(app, Story, \"stories\")\n\nThis produces the following views, a standard REST API!\n\n================= ========== ===================\nURL Method Description\n----------------- ---------- -------------------\n``/users/`` ``GET`` List all users\n``/users/`` ``POST`` Create a new user\n``/users/`` ``GET`` Show a single user\n``/users/`` ``PATCH`` Update a user\n``/users/`` ``DELETE`` Delete a user\n``/stories/`` ``GET`` List all stories\n``/stories/`` ``POST`` Create a new story\n``/stories/`` ``GET`` Show a single story\n``/stories/`` ``PATCH`` Update a story\n``/stories/`` ``DELETE`` Delete a story\n================= ========== ===================\n"},{"id":104,"name":"pyproject.toml","nodeType":"TextFile","path":"examples/celery","text":"[project]\nname = \"flask-example-celery\"\nversion = \"1.0.0\"\ndescription = \"Example Flask application with Celery background tasks.\"\nreadme = \"README.md\"\nrequires-python = \">=3.7\"\ndependencies = [\"flask>=2.2.2\", \"celery[redis]>=5.2.7\"]\n\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":105,"name":"application","nodeType":"Attribute","startLoc":3,"text":"application"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":20,"id":106,"name":"annotations","nodeType":"Attribute","startLoc":20,"text":"annotations"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":20,"id":107,"name":"annotations","nodeType":"Attribute","startLoc":20,"text":"annotations"},{"attributeType":"_Feature","col":0,"comment":"null","endLoc":20,"id":108,"name":"annotations","nodeType":"Attribute","startLoc":20,"text":"annotations"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":109,"name":"app","nodeType":"Attribute","startLoc":3,"text":"app"},{"col":0,"comment":"null","endLoc":5,"header":"def create_app()","id":110,"name":"create_app","nodeType":"Function","startLoc":4,"text":"def create_app():\n return Flask(\"app\")"},{"col":0,"comment":"null","endLoc":15,"header":"@admin.route(\"/\")\ndef index()","id":111,"name":"index","nodeType":"Function","startLoc":13,"text":"@admin.route(\"/\")\ndef index():\n return render_template(\"admin/index.html\")"},{"col":0,"comment":"null","endLoc":9,"header":"def create_app2(foo, bar)","id":112,"name":"create_app2","nodeType":"Function","startLoc":8,"text":"def create_app2(foo, bar):\n return Flask(\"_\".join([\"app2\", foo, bar]))"},{"fileName":"db.py","filePath":"examples/tutorial/flaskr","id":113,"nodeType":"File","text":"import sqlite3\n\nimport click\nfrom flask import current_app\nfrom flask import g\n\n\ndef get_db():\n \"\"\"Connect to the application's configured database. The connection\n is unique for each request and will be reused if this is called\n again.\n \"\"\"\n if \"db\" not in g:\n g.db = sqlite3.connect(\n current_app.config[\"DATABASE\"], detect_types=sqlite3.PARSE_DECLTYPES\n )\n g.db.row_factory = sqlite3.Row\n\n return g.db\n\n\ndef close_db(e=None):\n \"\"\"If this request connected to the database, close the\n connection.\n \"\"\"\n db = g.pop(\"db\", None)\n\n if db is not None:\n db.close()\n\n\ndef init_db():\n \"\"\"Clear existing data and create new tables.\"\"\"\n db = get_db()\n\n with current_app.open_resource(\"schema.sql\") as f:\n db.executescript(f.read().decode(\"utf8\"))\n\n\n@click.command(\"init-db\")\ndef init_db_command():\n \"\"\"Clear existing data and create new tables.\"\"\"\n init_db()\n click.echo(\"Initialized the database.\")\n\n\ndef init_app(app):\n \"\"\"Register database functions with the Flask app. This is called by\n the application factory.\n \"\"\"\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)\n"},{"fileName":"globals.py","filePath":"src/flask","id":114,"nodeType":"File","text":"import typing as t\nfrom contextvars import ContextVar\n\nfrom werkzeug.local import LocalProxy\n\nif t.TYPE_CHECKING: # pragma: no cover\n from .app import Flask\n from .ctx import _AppCtxGlobals\n from .ctx import AppContext\n from .ctx import RequestContext\n from .sessions import SessionMixin\n from .wrappers import Request\n\n\nclass _FakeStack:\n def __init__(self, name: str, cv: ContextVar[t.Any]) -> None:\n self.name = name\n self.cv = cv\n\n @property\n def top(self) -> t.Optional[t.Any]:\n import warnings\n\n warnings.warn(\n f\"'_{self.name}_ctx_stack' is deprecated and will be removed in Flask 2.4.\"\n f\" Use 'g' to store data, or '{self.name}_ctx' to access the current\"\n \" context.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return self.cv.get(None)\n\n\n_no_app_msg = \"\"\"\\\nWorking outside of application context.\n\nThis typically means that you attempted to use functionality that needed\nthe current application. To solve this, set up an application context\nwith app.app_context(). See the documentation for more information.\\\n\"\"\"\n_cv_app: ContextVar[\"AppContext\"] = ContextVar(\"flask.app_ctx\")\n__app_ctx_stack = _FakeStack(\"app\", _cv_app)\napp_ctx: \"AppContext\" = LocalProxy( # type: ignore[assignment]\n _cv_app, unbound_message=_no_app_msg\n)\ncurrent_app: \"Flask\" = LocalProxy( # type: ignore[assignment]\n _cv_app, \"app\", unbound_message=_no_app_msg\n)\ng: \"_AppCtxGlobals\" = LocalProxy( # type: ignore[assignment]\n _cv_app, \"g\", unbound_message=_no_app_msg\n)\n\n_no_req_msg = \"\"\"\\\nWorking outside of request context.\n\nThis typically means that you attempted to use functionality that needed\nan active HTTP request. Consult the documentation on testing for\ninformation about how to avoid this problem.\\\n\"\"\"\n_cv_request: ContextVar[\"RequestContext\"] = ContextVar(\"flask.request_ctx\")\n__request_ctx_stack = _FakeStack(\"request\", _cv_request)\nrequest_ctx: \"RequestContext\" = LocalProxy( # type: ignore[assignment]\n _cv_request, unbound_message=_no_req_msg\n)\nrequest: \"Request\" = LocalProxy( # type: ignore[assignment]\n _cv_request, \"request\", unbound_message=_no_req_msg\n)\nsession: \"SessionMixin\" = LocalProxy( # type: ignore[assignment]\n _cv_request, \"session\", unbound_message=_no_req_msg\n)\n\n\ndef __getattr__(name: str) -> t.Any:\n if name == \"_app_ctx_stack\":\n import warnings\n\n warnings.warn(\n \"'_app_ctx_stack' is deprecated and will be removed in Flask 2.4.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return __app_ctx_stack\n\n if name == \"_request_ctx_stack\":\n import warnings\n\n warnings.warn(\n \"'_request_ctx_stack' is deprecated and will be removed in Flask 2.4.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return __request_ctx_stack\n\n raise AttributeError(name)\n"},{"id":115,"name":"cli.rst","nodeType":"TextFile","path":"docs","text":".. currentmodule:: flask\n\nCommand Line Interface\n======================\n\nInstalling Flask installs the ``flask`` script, a `Click`_ command line\ninterface, in your virtualenv. Executed from the terminal, this script gives\naccess to built-in, extension, and application-defined commands. The ``--help``\noption will give more information about any commands and options.\n\n.. _Click: https://click.palletsprojects.com/\n\n\nApplication Discovery\n---------------------\n\nThe ``flask`` command is installed by Flask, not your application; it must be\ntold where to find your application in order to use it. The ``--app``\noption is used to specify how to load the application.\n\nWhile ``--app`` supports a variety of options for specifying your\napplication, most use cases should be simple. Here are the typical values:\n\n(nothing)\n The name \"app\" or \"wsgi\" is imported (as a \".py\" file, or package),\n automatically detecting an app (``app`` or ``application``) or\n factory (``create_app`` or ``make_app``).\n\n``--app hello``\n The given name is imported, automatically detecting an app (``app``\n or ``application``) or factory (``create_app`` or ``make_app``).\n\n----\n\n``--app`` has three parts: an optional path that sets the current working\ndirectory, a Python file or dotted import path, and an optional variable\nname of the instance or factory. If the name is a factory, it can optionally\nbe followed by arguments in parentheses. The following values demonstrate these\nparts:\n\n``--app src/hello``\n Sets the current working directory to ``src`` then imports ``hello``.\n\n``--app hello.web``\n Imports the path ``hello.web``.\n\n``--app hello:app2``\n Uses the ``app2`` Flask instance in ``hello``.\n\n``--app 'hello:create_app(\"dev\")'``\n The ``create_app`` factory in ``hello`` is called with the string ``'dev'``\n as the argument.\n\nIf ``--app`` is not set, the command will try to import \"app\" or\n\"wsgi\" (as a \".py\" file, or package) and try to detect an application\ninstance or factory.\n\nWithin the given import, the command looks for an application instance named\n``app`` or ``application``, then any application instance. If no instance is\nfound, the command looks for a factory function named ``create_app`` or\n``make_app`` that returns an instance.\n\nIf parentheses follow the factory name, their contents are parsed as\nPython literals and passed as arguments and keyword arguments to the\nfunction. This means that strings must still be in quotes.\n\n\nRun the Development Server\n--------------------------\n\nThe :func:`run ` command will start the development server. It\nreplaces the :meth:`Flask.run` method in most cases. ::\n\n $ flask --app hello run\n * Serving Flask app \"hello\"\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n\n.. warning:: Do not use this command to run your application in production.\n Only use the development server during development. The development server\n is provided for convenience, but is not designed to be particularly secure,\n stable, or efficient. See :doc:`/deploying/index` for how to run in production.\n\nIf another program is already using port 5000, you'll see\n``OSError: [Errno 98]`` or ``OSError: [WinError 10013]`` when the\nserver tries to start. See :ref:`address-already-in-use` for how to\nhandle that.\n\n\nDebug Mode\n~~~~~~~~~~\n\nIn debug mode, the ``flask run`` command will enable the interactive debugger and the\nreloader by default, and make errors easier to see and debug. To enable debug mode, use\nthe ``--debug`` option.\n\n.. code-block:: console\n\n $ flask --app hello run --debug\n * Serving Flask app \"hello\"\n * Debug mode: on\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n * Restarting with inotify reloader\n * Debugger is active!\n * Debugger PIN: 223-456-919\n\nThe ``--debug`` option can also be passed to the top level ``flask`` command to enable\ndebug mode for any command. The following two ``run`` calls are equivalent.\n\n.. code-block:: console\n\n $ flask --app hello --debug run\n $ flask --app hello run --debug\n\n\nWatch and Ignore Files with the Reloader\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen using debug mode, the reloader will trigger whenever your Python code or imported\nmodules change. The reloader can watch additional files with the ``--extra-files``\noption. Multiple paths are separated with ``:``, or ``;`` on Windows.\n\n.. code-block:: text\n\n $ flask run --extra-files file1:dirA/file2:dirB/\n * Running on http://127.0.0.1:8000/\n * Detected change in '/path/to/file1', reloading\n\nThe reloader can also ignore files using :mod:`fnmatch` patterns with the\n``--exclude-patterns`` option. Multiple patterns are separated with ``:``, or ``;`` on\nWindows.\n\n\nOpen a Shell\n------------\n\nTo explore the data in your application, you can start an interactive Python\nshell with the :func:`shell ` command. An application\ncontext will be active, and the app instance will be imported. ::\n\n $ flask shell\n Python 3.10.0 (default, Oct 27 2021, 06:59:51) [GCC 11.1.0] on linux\n App: example [production]\n Instance: /home/david/Projects/pallets/flask/instance\n >>>\n\nUse :meth:`~Flask.shell_context_processor` to add other automatic imports.\n\n\n.. _dotenv:\n\nEnvironment Variables From dotenv\n---------------------------------\n\nThe ``flask`` command supports setting any option for any command with\nenvironment variables. The variables are named like ``FLASK_OPTION`` or\n``FLASK_COMMAND_OPTION``, for example ``FLASK_APP`` or\n``FLASK_RUN_PORT``.\n\nRather than passing options every time you run a command, or environment\nvariables every time you open a new terminal, you can use Flask's dotenv\nsupport to set environment variables automatically.\n\nIf `python-dotenv`_ is installed, running the ``flask`` command will set\nenvironment variables defined in the files ``.env`` and ``.flaskenv``.\nYou can also specify an extra file to load with the ``--env-file``\noption. Dotenv files can be used to avoid having to set ``--app`` or\n``FLASK_APP`` manually, and to set configuration using environment\nvariables similar to how some deployment services work.\n\nVariables set on the command line are used over those set in :file:`.env`,\nwhich are used over those set in :file:`.flaskenv`. :file:`.flaskenv` should be\nused for public variables, such as ``FLASK_APP``, while :file:`.env` should not\nbe committed to your repository so that it can set private variables.\n\nDirectories are scanned upwards from the directory you call ``flask``\nfrom to locate the files.\n\nThe files are only loaded by the ``flask`` command or calling\n:meth:`~Flask.run`. If you would like to load these files when running in\nproduction, you should call :func:`~cli.load_dotenv` manually.\n\n.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme\n\n\nSetting Command Options\n~~~~~~~~~~~~~~~~~~~~~~~\n\nClick is configured to load default values for command options from\nenvironment variables. The variables use the pattern\n``FLASK_COMMAND_OPTION``. For example, to set the port for the run\ncommand, instead of ``flask run --port 8000``:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_RUN_PORT=8000\n $ flask run\n * Running on http://127.0.0.1:8000/\n\n .. group-tab:: Fish\n\n .. code-block:: text\n\n $ set -x FLASK_RUN_PORT 8000\n $ flask run\n * Running on http://127.0.0.1:8000/\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_RUN_PORT=8000\n > flask run\n * Running on http://127.0.0.1:8000/\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_RUN_PORT = 8000\n > flask run\n * Running on http://127.0.0.1:8000/\n\nThese can be added to the ``.flaskenv`` file just like ``FLASK_APP`` to\ncontrol default command options.\n\n\nDisable dotenv\n~~~~~~~~~~~~~~\n\nThe ``flask`` command will show a message if it detects dotenv files but\npython-dotenv is not installed.\n\n.. code-block:: bash\n\n $ flask run\n * Tip: There are .env files present. Do \"pip install python-dotenv\" to use them.\n\nYou can tell Flask not to load dotenv files even when python-dotenv is\ninstalled by setting the ``FLASK_SKIP_DOTENV`` environment variable.\nThis can be useful if you want to load them manually, or if you're using\na project runner that loads them already. Keep in mind that the\nenvironment variables must be set before the app loads or it won't\nconfigure as expected.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_SKIP_DOTENV=1\n $ flask run\n\n .. group-tab:: Fish\n\n .. code-block:: text\n\n $ set -x FLASK_SKIP_DOTENV 1\n $ flask run\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_SKIP_DOTENV=1\n > flask run\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_SKIP_DOTENV = 1\n > flask run\n\n\nEnvironment Variables From virtualenv\n-------------------------------------\n\nIf you do not want to install dotenv support, you can still set environment\nvariables by adding them to the end of the virtualenv's :file:`activate`\nscript. Activating the virtualenv will set the variables.\n\n.. tabs::\n\n .. group-tab:: Bash\n\n Unix Bash, :file:`.venv/bin/activate`::\n\n $ export FLASK_APP=hello\n\n .. group-tab:: Fish\n\n Fish, :file:`.venv/bin/activate.fish`::\n\n $ set -x FLASK_APP hello\n\n .. group-tab:: CMD\n\n Windows CMD, :file:`.venv\\\\Scripts\\\\activate.bat`::\n\n > set FLASK_APP=hello\n\n .. group-tab:: Powershell\n\n Windows Powershell, :file:`.venv\\\\Scripts\\\\activate.ps1`::\n\n > $env:FLASK_APP = \"hello\"\n\nIt is preferred to use dotenv support over this, since :file:`.flaskenv` can be\ncommitted to the repository so that it works automatically wherever the project\nis checked out.\n\n\nCustom Commands\n---------------\n\nThe ``flask`` command is implemented using `Click`_. See that project's\ndocumentation for full information about writing commands.\n\nThis example adds the command ``create-user`` that takes the argument\n``name``. ::\n\n import click\n from flask import Flask\n\n app = Flask(__name__)\n\n @app.cli.command(\"create-user\")\n @click.argument(\"name\")\n def create_user(name):\n ...\n\n::\n\n $ flask create-user admin\n\nThis example adds the same command, but as ``user create``, a command in a\ngroup. This is useful if you want to organize multiple related commands. ::\n\n import click\n from flask import Flask\n from flask.cli import AppGroup\n\n app = Flask(__name__)\n user_cli = AppGroup('user')\n\n @user_cli.command('create')\n @click.argument('name')\n def create_user(name):\n ...\n\n app.cli.add_command(user_cli)\n\n::\n\n $ flask user create demo\n\nSee :ref:`testing-cli` for an overview of how to test your custom\ncommands.\n\n\nRegistering Commands with Blueprints\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf your application uses blueprints, you can optionally register CLI\ncommands directly onto them. When your blueprint is registered onto your\napplication, the associated commands will be available to the ``flask``\ncommand. By default, those commands will be nested in a group matching\nthe name of the blueprint.\n\n.. code-block:: python\n\n from flask import Blueprint\n\n bp = Blueprint('students', __name__)\n\n @bp.cli.command('create')\n @click.argument('name')\n def create(name):\n ...\n\n app.register_blueprint(bp)\n\n.. code-block:: text\n\n $ flask students create alice\n\nYou can alter the group name by specifying the ``cli_group`` parameter\nwhen creating the :class:`Blueprint` object, or later with\n:meth:`app.register_blueprint(bp, cli_group='...') `.\nThe following are equivalent:\n\n.. code-block:: python\n\n bp = Blueprint('students', __name__, cli_group='other')\n # or\n app.register_blueprint(bp, cli_group='other')\n\n.. code-block:: text\n\n $ flask other create alice\n\nSpecifying ``cli_group=None`` will remove the nesting and merge the\ncommands directly to the application's level:\n\n.. code-block:: python\n\n bp = Blueprint('students', __name__, cli_group=None)\n # or\n app.register_blueprint(bp, cli_group=None)\n\n.. code-block:: text\n\n $ flask create alice\n\n\nApplication Context\n~~~~~~~~~~~~~~~~~~~\n\nCommands added using the Flask app's :attr:`~Flask.cli` or\n:class:`~flask.cli.FlaskGroup` :meth:`~cli.AppGroup.command` decorator\nwill be executed with an application context pushed, so your custom\ncommands and parameters have access to the app and its configuration. The\n:func:`~cli.with_appcontext` decorator can be used to get the same\nbehavior, but is not needed in most cases.\n\n.. code-block:: python\n\n import click\n from flask.cli import with_appcontext\n\n @click.command()\n @with_appcontext\n def do_work():\n ...\n\n app.cli.add_command(do_work)\n\n\nPlugins\n-------\n\nFlask will automatically load commands specified in the ``flask.commands``\n`entry point`_. This is useful for extensions that want to add commands when\nthey are installed. Entry points are specified in :file:`pyproject.toml`:\n\n.. code-block:: toml\n\n [project.entry-points.\"flask.commands\"]\n my-command = \"my_extension.commands:cli\"\n\n.. _entry point: https://packaging.python.org/tutorials/packaging-projects/#entry-points\n\nInside :file:`my_extension/commands.py` you can then export a Click\nobject::\n\n import click\n\n @click.command()\n def cli():\n ...\n\nOnce that package is installed in the same virtualenv as your Flask project,\nyou can run ``flask my-command`` to invoke the command.\n\n\n.. _custom-scripts:\n\nCustom Scripts\n--------------\n\nWhen you are using the app factory pattern, it may be more convenient to define\nyour own Click script. Instead of using ``--app`` and letting Flask load\nyour application, you can create your own Click object and export it as a\n`console script`_ entry point.\n\nCreate an instance of :class:`~cli.FlaskGroup` and pass it the factory::\n\n import click\n from flask import Flask\n from flask.cli import FlaskGroup\n\n def create_app():\n app = Flask('wiki')\n # other setup\n return app\n\n @click.group(cls=FlaskGroup, create_app=create_app)\n def cli():\n \"\"\"Management script for the Wiki application.\"\"\"\n\nDefine the entry point in :file:`pyproject.toml`:\n\n.. code-block:: toml\n\n [project.scripts]\n wiki = \"wiki:cli\"\n\nInstall the application in the virtualenv in editable mode and the custom\nscript is available. Note that you don't need to set ``--app``. ::\n\n $ pip install -e .\n $ wiki run\n\n.. admonition:: Errors in Custom Scripts\n\n When using a custom script, if you introduce an error in your\n module-level code, the reloader will fail because it can no longer\n load the entry point.\n\n The ``flask`` command, being separate from your code, does not have\n this issue and is recommended in most cases.\n\n.. _console script: https://packaging.python.org/tutorials/packaging-projects/#console-scripts\n\n\nPyCharm Integration\n-------------------\n\nPyCharm Professional provides a special Flask run configuration to run the development\nserver. For the Community Edition, and for other commands besides ``run``, you need to\ncreate a custom run configuration. These instructions should be similar for any other\nIDE you use.\n\nIn PyCharm, with your project open, click on *Run* from the menu bar and go to *Edit\nConfigurations*. You'll see a screen similar to this:\n\n.. image:: _static/pycharm-run-config.png\n :align: center\n :class: screenshot\n :alt: Screenshot of PyCharm run configuration.\n\nOnce you create a configuration for the ``flask run``, you can copy and change it to\ncall any other command.\n\nClick the *+ (Add New Configuration)* button and select *Python*. Give the configuration\na name such as \"flask run\".\n\nClick the *Script path* dropdown and change it to *Module name*, then input ``flask``.\n\nThe *Parameters* field is set to the CLI command to execute along with any arguments.\nThis example uses ``--app hello run --debug``, which will run the development server in\ndebug mode. ``--app hello`` should be the import or file with your Flask app.\n\nIf you installed your project as a package in your virtualenv, you may uncheck the\n*PYTHONPATH* options. This will more accurately match how you deploy later.\n\nClick *OK* to save and close the configuration. Select the configuration in the main\nPyCharm window and click the play button next to it to run the server.\n\nNow that you have a configuration for ``flask run``, you can copy that configuration and\nchange the *Parameters* argument to run a different CLI command.\n"},{"id":116,"name":"examples/celery/src/task_app","nodeType":"Package"},{"fileName":"views.py","filePath":"examples/celery/src/task_app","id":117,"nodeType":"File","text":"from celery.result import AsyncResult\nfrom flask import Blueprint\nfrom flask import request\n\nfrom . import tasks\n\nbp = Blueprint(\"tasks\", __name__, url_prefix=\"/tasks\")\n\n\n@bp.get(\"/result/\")\ndef result(id: str) -> dict[str, object]:\n result = AsyncResult(id)\n ready = result.ready()\n return {\n \"ready\": ready,\n \"successful\": result.successful() if ready else None,\n \"value\": result.get() if ready else result.result,\n }\n\n\n@bp.post(\"/add\")\ndef add() -> dict[str, object]:\n a = request.form.get(\"a\", type=int)\n b = request.form.get(\"b\", type=int)\n result = tasks.add.delay(a, b)\n return {\"result_id\": result.id}\n\n\n@bp.post(\"/block\")\ndef block() -> dict[str, object]:\n result = tasks.block.delay()\n return {\"result_id\": result.id}\n\n\n@bp.post(\"/process\")\ndef process() -> dict[str, object]:\n result = tasks.process.delay(total=request.form.get(\"total\", type=int))\n return {\"result_id\": result.id}\n"},{"col":0,"comment":"Create and configure an instance of the Flask application.","endLoc":50,"header":"def create_app(test_config=None)","id":118,"name":"create_app","nodeType":"Function","startLoc":6,"text":"def create_app(test_config=None):\n \"\"\"Create and configure an instance of the Flask application.\"\"\"\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n # a default secret that should be overridden by instance config\n SECRET_KEY=\"dev\",\n # store the database in the instance folder\n DATABASE=os.path.join(app.instance_path, \"flaskr.sqlite\"),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile(\"config.py\", silent=True)\n else:\n # load the test config if passed in\n app.config.update(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n @app.route(\"/hello\")\n def hello():\n return \"Hello, World!\"\n\n # register the database commands\n from flaskr import db\n\n db.init_app(app)\n\n # apply the blueprints to the app\n from flaskr import auth, blog\n\n app.register_blueprint(auth.bp)\n app.register_blueprint(blog.bp)\n\n # make url_for('index') == url_for('blog.index')\n # in another app, you might define a separate main index here with\n # app.route, while giving the blog blueprint a url_prefix, but for\n # the tutorial the blog will be the main index\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n return app"},{"className":"Flask","col":0,"comment":"The flask object implements a WSGI application and acts as the central\n object. It is passed the name of the module or package of the\n application. Once it is created it will act as a central registry for\n the view functions, the URL rules, template configuration and much more.\n\n The name of the package is used to resolve resources from inside the\n package or the folder the module is contained in depending on if the\n package parameter resolves to an actual python package (a folder with\n an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n For more information about resource loading, see :func:`open_resource`.\n\n Usually you create a :class:`Flask` instance in your main module or\n in the :file:`__init__.py` file of your package like this::\n\n from flask import Flask\n app = Flask(__name__)\n\n .. admonition:: About the First Parameter\n\n The idea of the first parameter is to give Flask an idea of what\n belongs to your application. This name is used to find resources\n on the filesystem, can be used by extensions to improve debugging\n information and a lot more.\n\n So it's important what you provide there. If you are using a single\n module, `__name__` is always the correct value. If you however are\n using a package, it's usually recommended to hardcode the name of\n your package there.\n\n For example if your application is defined in :file:`yourapplication/app.py`\n you should create it with one of the two versions below::\n\n app = Flask('yourapplication')\n app = Flask(__name__.split('.')[0])\n\n Why is that? The application will work even with `__name__`, thanks\n to how resources are looked up. However it will make debugging more\n painful. Certain extensions can make assumptions based on the\n import name of your application. For example the Flask-SQLAlchemy\n extension will look for the code in your application that triggered\n an SQL query in debug mode. If the import name is not properly set\n up, that debugging information is lost. (For example it would only\n pick up SQL queries in `yourapplication.app` and not\n `yourapplication.views.frontend`)\n\n .. versionadded:: 0.7\n The `static_url_path`, `static_folder`, and `template_folder`\n parameters were added.\n\n .. versionadded:: 0.8\n The `instance_path` and `instance_relative_config` parameters were\n added.\n\n .. versionadded:: 0.11\n The `root_path` parameter was added.\n\n .. versionadded:: 1.0\n The ``host_matching`` and ``static_host`` parameters were added.\n\n .. versionadded:: 1.0\n The ``subdomain_matching`` parameter was added. Subdomain\n matching needs to be enabled manually now. Setting\n :data:`SERVER_NAME` does not implicitly enable it.\n\n :param import_name: the name of the application package\n :param static_url_path: can be used to specify a different path for the\n static files on the web. Defaults to the name\n of the `static_folder` folder.\n :param static_folder: The folder with static files that is served at\n ``static_url_path``. Relative to the application ``root_path``\n or an absolute path. Defaults to ``'static'``.\n :param static_host: the host to use when adding the static route.\n Defaults to None. Required when using ``host_matching=True``\n with a ``static_folder`` configured.\n :param host_matching: set ``url_map.host_matching`` attribute.\n Defaults to False.\n :param subdomain_matching: consider the subdomain relative to\n :data:`SERVER_NAME` when matching routes. Defaults to False.\n :param template_folder: the folder that contains the templates that should\n be used by the application. Defaults to\n ``'templates'`` folder in the root path of the\n application.\n :param instance_path: An alternative instance path for the application.\n By default the folder ``'instance'`` next to the\n package or module is assumed to be the instance\n path.\n :param instance_relative_config: if set to ``True`` relative filenames\n for loading the config are assumed to\n be relative to the instance path instead\n of the application root.\n :param root_path: The path to the root of the application files.\n This should only be set manually when it can't be detected\n automatically, such as for namespace packages.\n ","endLoc":2230,"id":119,"nodeType":"Class","startLoc":105,"text":"class Flask(Scaffold):\n \"\"\"The flask object implements a WSGI application and acts as the central\n object. It is passed the name of the module or package of the\n application. Once it is created it will act as a central registry for\n the view functions, the URL rules, template configuration and much more.\n\n The name of the package is used to resolve resources from inside the\n package or the folder the module is contained in depending on if the\n package parameter resolves to an actual python package (a folder with\n an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).\n\n For more information about resource loading, see :func:`open_resource`.\n\n Usually you create a :class:`Flask` instance in your main module or\n in the :file:`__init__.py` file of your package like this::\n\n from flask import Flask\n app = Flask(__name__)\n\n .. admonition:: About the First Parameter\n\n The idea of the first parameter is to give Flask an idea of what\n belongs to your application. This name is used to find resources\n on the filesystem, can be used by extensions to improve debugging\n information and a lot more.\n\n So it's important what you provide there. If you are using a single\n module, `__name__` is always the correct value. If you however are\n using a package, it's usually recommended to hardcode the name of\n your package there.\n\n For example if your application is defined in :file:`yourapplication/app.py`\n you should create it with one of the two versions below::\n\n app = Flask('yourapplication')\n app = Flask(__name__.split('.')[0])\n\n Why is that? The application will work even with `__name__`, thanks\n to how resources are looked up. However it will make debugging more\n painful. Certain extensions can make assumptions based on the\n import name of your application. For example the Flask-SQLAlchemy\n extension will look for the code in your application that triggered\n an SQL query in debug mode. If the import name is not properly set\n up, that debugging information is lost. (For example it would only\n pick up SQL queries in `yourapplication.app` and not\n `yourapplication.views.frontend`)\n\n .. versionadded:: 0.7\n The `static_url_path`, `static_folder`, and `template_folder`\n parameters were added.\n\n .. versionadded:: 0.8\n The `instance_path` and `instance_relative_config` parameters were\n added.\n\n .. versionadded:: 0.11\n The `root_path` parameter was added.\n\n .. versionadded:: 1.0\n The ``host_matching`` and ``static_host`` parameters were added.\n\n .. versionadded:: 1.0\n The ``subdomain_matching`` parameter was added. Subdomain\n matching needs to be enabled manually now. Setting\n :data:`SERVER_NAME` does not implicitly enable it.\n\n :param import_name: the name of the application package\n :param static_url_path: can be used to specify a different path for the\n static files on the web. Defaults to the name\n of the `static_folder` folder.\n :param static_folder: The folder with static files that is served at\n ``static_url_path``. Relative to the application ``root_path``\n or an absolute path. Defaults to ``'static'``.\n :param static_host: the host to use when adding the static route.\n Defaults to None. Required when using ``host_matching=True``\n with a ``static_folder`` configured.\n :param host_matching: set ``url_map.host_matching`` attribute.\n Defaults to False.\n :param subdomain_matching: consider the subdomain relative to\n :data:`SERVER_NAME` when matching routes. Defaults to False.\n :param template_folder: the folder that contains the templates that should\n be used by the application. Defaults to\n ``'templates'`` folder in the root path of the\n application.\n :param instance_path: An alternative instance path for the application.\n By default the folder ``'instance'`` next to the\n package or module is assumed to be the instance\n path.\n :param instance_relative_config: if set to ``True`` relative filenames\n for loading the config are assumed to\n be relative to the instance path instead\n of the application root.\n :param root_path: The path to the root of the application files.\n This should only be set manually when it can't be detected\n automatically, such as for namespace packages.\n \"\"\"\n\n #: The class that is used for request objects. See :class:`~flask.Request`\n #: for more information.\n request_class = Request\n\n #: The class that is used for response objects. See\n #: :class:`~flask.Response` for more information.\n response_class = Response\n\n #: The class of the object assigned to :attr:`aborter`, created by\n #: :meth:`create_aborter`. That object is called by\n #: :func:`flask.abort` to raise HTTP errors, and can be\n #: called directly as well.\n #:\n #: Defaults to :class:`werkzeug.exceptions.Aborter`.\n #:\n #: .. versionadded:: 2.2\n aborter_class = Aborter\n\n #: The class that is used for the Jinja environment.\n #:\n #: .. versionadded:: 0.11\n jinja_environment = Environment\n\n #: The class that is used for the :data:`~flask.g` instance.\n #:\n #: Example use cases for a custom class:\n #:\n #: 1. Store arbitrary attributes on flask.g.\n #: 2. Add a property for lazy per-request database connectors.\n #: 3. Return None instead of AttributeError on unexpected attributes.\n #: 4. Raise exception if an unexpected attr is set, a \"controlled\" flask.g.\n #:\n #: In Flask 0.9 this property was called `request_globals_class` but it\n #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the\n #: flask.g object is now application context scoped.\n #:\n #: .. versionadded:: 0.10\n app_ctx_globals_class = _AppCtxGlobals\n\n #: The class that is used for the ``config`` attribute of this app.\n #: Defaults to :class:`~flask.Config`.\n #:\n #: Example use cases for a custom class:\n #:\n #: 1. Default values for certain config options.\n #: 2. Access to config values through attributes in addition to keys.\n #:\n #: .. versionadded:: 0.11\n config_class = Config\n\n #: The testing flag. Set this to ``True`` to enable the test mode of\n #: Flask extensions (and in the future probably also Flask itself).\n #: For example this might activate test helpers that have an\n #: additional runtime cost which should not be enabled by default.\n #:\n #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the\n #: default it's implicitly enabled.\n #:\n #: This attribute can also be configured from the config with the\n #: ``TESTING`` configuration key. Defaults to ``False``.\n testing = ConfigAttribute(\"TESTING\")\n\n #: If a secret key is set, cryptographic components can use this to\n #: sign cookies and other things. Set this to a complex random value\n #: when you want to use the secure cookie for instance.\n #:\n #: This attribute can also be configured from the config with the\n #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.\n secret_key = ConfigAttribute(\"SECRET_KEY\")\n\n #: A :class:`~datetime.timedelta` which is used to set the expiration\n #: date of a permanent session. The default is 31 days which makes a\n #: permanent session survive for roughly one month.\n #:\n #: This attribute can also be configured from the config with the\n #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to\n #: ``timedelta(days=31)``\n permanent_session_lifetime = ConfigAttribute(\n \"PERMANENT_SESSION_LIFETIME\", get_converter=_make_timedelta\n )\n\n json_provider_class: t.Type[JSONProvider] = DefaultJSONProvider\n \"\"\"A subclass of :class:`~flask.json.provider.JSONProvider`. An\n instance is created and assigned to :attr:`app.json` when creating\n the app.\n\n The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses\n Python's built-in :mod:`json` library. A different provider can use\n a different JSON library.\n\n .. versionadded:: 2.2\n \"\"\"\n\n #: Options that are passed to the Jinja environment in\n #: :meth:`create_jinja_environment`. Changing these options after\n #: the environment is created (accessing :attr:`jinja_env`) will\n #: have no effect.\n #:\n #: .. versionchanged:: 1.1.0\n #: This is a ``dict`` instead of an ``ImmutableDict`` to allow\n #: easier configuration.\n #:\n jinja_options: dict = {}\n\n #: Default configuration parameters.\n default_config = ImmutableDict(\n {\n \"DEBUG\": None,\n \"TESTING\": False,\n \"PROPAGATE_EXCEPTIONS\": None,\n \"SECRET_KEY\": None,\n \"PERMANENT_SESSION_LIFETIME\": timedelta(days=31),\n \"USE_X_SENDFILE\": False,\n \"SERVER_NAME\": None,\n \"APPLICATION_ROOT\": \"/\",\n \"SESSION_COOKIE_NAME\": \"session\",\n \"SESSION_COOKIE_DOMAIN\": None,\n \"SESSION_COOKIE_PATH\": None,\n \"SESSION_COOKIE_HTTPONLY\": True,\n \"SESSION_COOKIE_SECURE\": False,\n \"SESSION_COOKIE_SAMESITE\": None,\n \"SESSION_REFRESH_EACH_REQUEST\": True,\n \"MAX_CONTENT_LENGTH\": None,\n \"SEND_FILE_MAX_AGE_DEFAULT\": None,\n \"TRAP_BAD_REQUEST_ERRORS\": None,\n \"TRAP_HTTP_EXCEPTIONS\": False,\n \"EXPLAIN_TEMPLATE_LOADING\": False,\n \"PREFERRED_URL_SCHEME\": \"http\",\n \"TEMPLATES_AUTO_RELOAD\": None,\n \"MAX_COOKIE_SIZE\": 4093,\n }\n )\n\n #: The rule object to use for URL rules created. This is used by\n #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.\n #:\n #: .. versionadded:: 0.7\n url_rule_class = Rule\n\n #: The map object to use for storing the URL rules and routing\n #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.\n #:\n #: .. versionadded:: 1.1.0\n url_map_class = Map\n\n #: The :meth:`test_client` method creates an instance of this test\n #: client class. Defaults to :class:`~flask.testing.FlaskClient`.\n #:\n #: .. versionadded:: 0.7\n test_client_class: t.Optional[t.Type[\"FlaskClient\"]] = None\n\n #: The :class:`~click.testing.CliRunner` subclass, by default\n #: :class:`~flask.testing.FlaskCliRunner` that is used by\n #: :meth:`test_cli_runner`. Its ``__init__`` method should take a\n #: Flask app object as the first argument.\n #:\n #: .. versionadded:: 1.0\n test_cli_runner_class: t.Optional[t.Type[\"FlaskCliRunner\"]] = None\n\n #: the session interface to use. By default an instance of\n #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.\n #:\n #: .. versionadded:: 0.8\n session_interface: SessionInterface = SecureCookieSessionInterface()\n\n def __init__(\n self,\n import_name: str,\n static_url_path: t.Optional[str] = None,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = \"static\",\n static_host: t.Optional[str] = None,\n host_matching: bool = False,\n subdomain_matching: bool = False,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = \"templates\",\n instance_path: t.Optional[str] = None,\n instance_relative_config: bool = False,\n root_path: t.Optional[str] = None,\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n\n if instance_path is None:\n instance_path = self.auto_find_instance_path()\n elif not os.path.isabs(instance_path):\n raise ValueError(\n \"If an instance path is provided it must be absolute.\"\n \" A relative path was given instead.\"\n )\n\n #: Holds the path to the instance folder.\n #:\n #: .. versionadded:: 0.8\n self.instance_path = instance_path\n\n #: The configuration dictionary as :class:`Config`. This behaves\n #: exactly like a regular dictionary but supports additional methods\n #: to load a config from files.\n self.config = self.make_config(instance_relative_config)\n\n #: An instance of :attr:`aborter_class` created by\n #: :meth:`make_aborter`. This is called by :func:`flask.abort`\n #: to raise HTTP errors, and can be called directly as well.\n #:\n #: .. versionadded:: 2.2\n #: Moved from ``flask.abort``, which calls this object.\n self.aborter = self.make_aborter()\n\n self.json: JSONProvider = self.json_provider_class(self)\n \"\"\"Provides access to JSON methods. Functions in ``flask.json``\n will call methods on this provider when the application context\n is active. Used for handling JSON requests and responses.\n\n An instance of :attr:`json_provider_class`. Can be customized by\n changing that attribute on a subclass, or by assigning to this\n attribute afterwards.\n\n The default, :class:`~flask.json.provider.DefaultJSONProvider`,\n uses Python's built-in :mod:`json` library. A different provider\n can use a different JSON library.\n\n .. versionadded:: 2.2\n \"\"\"\n\n #: A list of functions that are called by\n #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a\n #: :exc:`~werkzeug.routing.BuildError`. Each function is called\n #: with ``error``, ``endpoint`` and ``values``. If a function\n #: returns ``None`` or raises a ``BuildError``, it is skipped.\n #: Otherwise, its return value is returned by ``url_for``.\n #:\n #: .. versionadded:: 0.9\n self.url_build_error_handlers: t.List[\n t.Callable[[Exception, str, t.Dict[str, t.Any]], str]\n ] = []\n\n #: A list of functions that are called when the application context\n #: is destroyed. Since the application context is also torn down\n #: if the request ends this is the place to store code that disconnects\n #: from databases.\n #:\n #: .. versionadded:: 0.9\n self.teardown_appcontext_funcs: t.List[ft.TeardownCallable] = []\n\n #: A list of shell context processor functions that should be run\n #: when a shell context is created.\n #:\n #: .. versionadded:: 0.11\n self.shell_context_processors: t.List[ft.ShellContextProcessorCallable] = []\n\n #: Maps registered blueprint names to blueprint objects. The\n #: dict retains the order the blueprints were registered in.\n #: Blueprints can be registered multiple times, this dict does\n #: not track how often they were attached.\n #:\n #: .. versionadded:: 0.7\n self.blueprints: t.Dict[str, \"Blueprint\"] = {}\n\n #: a place where extensions can store application specific state. For\n #: example this is where an extension could store database engines and\n #: similar things.\n #:\n #: The key must match the name of the extension module. For example in\n #: case of a \"Flask-Foo\" extension in `flask_foo`, the key would be\n #: ``'foo'``.\n #:\n #: .. versionadded:: 0.7\n self.extensions: dict = {}\n\n #: The :class:`~werkzeug.routing.Map` for this instance. You can use\n #: this to change the routing converters after the class was created\n #: but before any routes are connected. Example::\n #:\n #: from werkzeug.routing import BaseConverter\n #:\n #: class ListConverter(BaseConverter):\n #: def to_python(self, value):\n #: return value.split(',')\n #: def to_url(self, values):\n #: return ','.join(super(ListConverter, self).to_url(value)\n #: for value in values)\n #:\n #: app = Flask(__name__)\n #: app.url_map.converters['list'] = ListConverter\n self.url_map = self.url_map_class()\n\n self.url_map.host_matching = host_matching\n self.subdomain_matching = subdomain_matching\n\n # tracks internally if the application already handled at least one\n # request.\n self._got_first_request = False\n\n # Add a static route using the provided static_url_path, static_host,\n # and static_folder if there is a configured static_folder.\n # Note we do this without checking if static_folder exists.\n # For one, it might be created while the server is running (e.g. during\n # development). Also, Google App Engine stores static files somewhere\n if self.has_static_folder:\n assert (\n bool(static_host) == host_matching\n ), \"Invalid static_host/host_matching combination\"\n # Use a weakref to avoid creating a reference cycle between the app\n # and the view function (see #3761).\n self_ref = weakref.ref(self)\n self.add_url_rule(\n f\"{self.static_url_path}/\",\n endpoint=\"static\",\n host=static_host,\n view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950\n )\n\n # Set the name of the Click group in case someone wants to add\n # the app's commands to another CLI tool.\n self.cli.name = self.name\n\n def _check_setup_finished(self, f_name: str) -> None:\n if self._got_first_request:\n raise AssertionError(\n f\"The setup method '{f_name}' can no longer be called\"\n \" on the application. It has already handled its first\"\n \" request, any changes will not be applied\"\n \" consistently.\\n\"\n \"Make sure all imports, decorators, functions, etc.\"\n \" needed to set up the application are done before\"\n \" running it.\"\n )\n\n @cached_property\n def name(self) -> str: # type: ignore\n \"\"\"The name of the application. This is usually the import name\n with the difference that it's guessed from the run file if the\n import name is main. This name is used as a display name when\n Flask needs the name of the application. It can be set and overridden\n to change the value.\n\n .. versionadded:: 0.8\n \"\"\"\n if self.import_name == \"__main__\":\n fn = getattr(sys.modules[\"__main__\"], \"__file__\", None)\n if fn is None:\n return \"__main__\"\n return os.path.splitext(os.path.basename(fn))[0]\n return self.import_name\n\n @cached_property\n def logger(self) -> logging.Logger:\n \"\"\"A standard Python :class:`~logging.Logger` for the app, with\n the same name as :attr:`name`.\n\n In debug mode, the logger's :attr:`~logging.Logger.level` will\n be set to :data:`~logging.DEBUG`.\n\n If there are no handlers configured, a default handler will be\n added. See :doc:`/logging` for more information.\n\n .. versionchanged:: 1.1.0\n The logger takes the same name as :attr:`name` rather than\n hard-coding ``\"flask.app\"``.\n\n .. versionchanged:: 1.0.0\n Behavior was simplified. The logger is always named\n ``\"flask.app\"``. The level is only set during configuration,\n it doesn't check ``app.debug`` each time. Only one format is\n used, not different ones depending on ``app.debug``. No\n handlers are removed, and a handler is only added if no\n handlers are already configured.\n\n .. versionadded:: 0.3\n \"\"\"\n return create_logger(self)\n\n @cached_property\n def jinja_env(self) -> Environment:\n \"\"\"The Jinja environment used to load templates.\n\n The environment is created the first time this property is\n accessed. Changing :attr:`jinja_options` after that will have no\n effect.\n \"\"\"\n return self.create_jinja_environment()\n\n @property\n def got_first_request(self) -> bool:\n \"\"\"This attribute is set to ``True`` if the application started\n handling the first request.\n\n .. deprecated:: 2.3\n Will be removed in Flask 2.4.\n\n .. versionadded:: 0.8\n \"\"\"\n import warnings\n\n warnings.warn(\n \"'got_first_request' is deprecated and will be removed in Flask 2.4.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return self._got_first_request\n\n def make_config(self, instance_relative: bool = False) -> Config:\n \"\"\"Used to create the config attribute by the Flask constructor.\n The `instance_relative` parameter is passed in from the constructor\n of Flask (there named `instance_relative_config`) and indicates if\n the config should be relative to the instance path or the root path\n of the application.\n\n .. versionadded:: 0.8\n \"\"\"\n root_path = self.root_path\n if instance_relative:\n root_path = self.instance_path\n defaults = dict(self.default_config)\n defaults[\"DEBUG\"] = get_debug_flag()\n return self.config_class(root_path, defaults)\n\n def make_aborter(self) -> Aborter:\n \"\"\"Create the object to assign to :attr:`aborter`. That object\n is called by :func:`flask.abort` to raise HTTP errors, and can\n be called directly as well.\n\n By default, this creates an instance of :attr:`aborter_class`,\n which defaults to :class:`werkzeug.exceptions.Aborter`.\n\n .. versionadded:: 2.2\n \"\"\"\n return self.aborter_class()\n\n def auto_find_instance_path(self) -> str:\n \"\"\"Tries to locate the instance path if it was not provided to the\n constructor of the application class. It will basically calculate\n the path to a folder named ``instance`` next to your main file or\n the package.\n\n .. versionadded:: 0.8\n \"\"\"\n prefix, package_path = find_package(self.import_name)\n if prefix is None:\n return os.path.join(package_path, \"instance\")\n return os.path.join(prefix, \"var\", f\"{self.name}-instance\")\n\n def open_instance_resource(self, resource: str, mode: str = \"rb\") -> t.IO[t.AnyStr]:\n \"\"\"Opens a resource from the application's instance folder\n (:attr:`instance_path`). Otherwise works like\n :meth:`open_resource`. Instance resources can also be opened for\n writing.\n\n :param resource: the name of the resource. To access resources within\n subfolders use forward slashes as separator.\n :param mode: resource file opening mode, default is 'rb'.\n \"\"\"\n return open(os.path.join(self.instance_path, resource), mode)\n\n def create_jinja_environment(self) -> Environment:\n \"\"\"Create the Jinja environment based on :attr:`jinja_options`\n and the various Jinja-related methods of the app. Changing\n :attr:`jinja_options` after this will have no effect. Also adds\n Flask-related globals and filters to the environment.\n\n .. versionchanged:: 0.11\n ``Environment.auto_reload`` set in accordance with\n ``TEMPLATES_AUTO_RELOAD`` configuration option.\n\n .. versionadded:: 0.5\n \"\"\"\n options = dict(self.jinja_options)\n\n if \"autoescape\" not in options:\n options[\"autoescape\"] = self.select_jinja_autoescape\n\n if \"auto_reload\" not in options:\n auto_reload = self.config[\"TEMPLATES_AUTO_RELOAD\"]\n\n if auto_reload is None:\n auto_reload = self.debug\n\n options[\"auto_reload\"] = auto_reload\n\n rv = self.jinja_environment(self, **options)\n rv.globals.update(\n url_for=self.url_for,\n get_flashed_messages=get_flashed_messages,\n config=self.config,\n # request, session and g are normally added with the\n # context processor for efficiency reasons but for imported\n # templates we also want the proxies in there.\n request=request,\n session=session,\n g=g,\n )\n rv.policies[\"json.dumps_function\"] = self.json.dumps\n return rv\n\n def create_global_jinja_loader(self) -> DispatchingJinjaLoader:\n \"\"\"Creates the loader for the Jinja2 environment. Can be used to\n override just the loader and keeping the rest unchanged. It's\n discouraged to override this function. Instead one should override\n the :meth:`jinja_loader` function instead.\n\n The global loader dispatches between the loaders of the application\n and the individual blueprints.\n\n .. versionadded:: 0.7\n \"\"\"\n return DispatchingJinjaLoader(self)\n\n def select_jinja_autoescape(self, filename: str) -> bool:\n \"\"\"Returns ``True`` if autoescaping should be active for the given\n template name. If no template name is given, returns `True`.\n\n .. versionchanged:: 2.2\n Autoescaping is now enabled by default for ``.svg`` files.\n\n .. versionadded:: 0.5\n \"\"\"\n if filename is None:\n return True\n return filename.endswith((\".html\", \".htm\", \".xml\", \".xhtml\", \".svg\"))\n\n def update_template_context(self, context: dict) -> None:\n \"\"\"Update the template context with some commonly used variables.\n This injects request, session, config and g into the template\n context as well as everything template context processors want\n to inject. Note that the as of Flask 0.6, the original values\n in the context will not be overridden if a context processor\n decides to return a value with the same key.\n\n :param context: the context as a dictionary that is updated in place\n to add extra variables.\n \"\"\"\n names: t.Iterable[t.Optional[str]] = (None,)\n\n # A template may be rendered outside a request context.\n if request:\n names = chain(names, reversed(request.blueprints))\n\n # The values passed to render_template take precedence. Keep a\n # copy to re-apply after all context functions.\n orig_ctx = context.copy()\n\n for name in names:\n if name in self.template_context_processors:\n for func in self.template_context_processors[name]:\n context.update(func())\n\n context.update(orig_ctx)\n\n def make_shell_context(self) -> dict:\n \"\"\"Returns the shell context for an interactive shell for this\n application. This runs all the registered shell context\n processors.\n\n .. versionadded:: 0.11\n \"\"\"\n rv = {\"app\": self, \"g\": g}\n for processor in self.shell_context_processors:\n rv.update(processor())\n return rv\n\n @property\n def debug(self) -> bool:\n \"\"\"Whether debug mode is enabled. When using ``flask run`` to start the\n development server, an interactive debugger will be shown for unhandled\n exceptions, and the server will be reloaded when code changes. This maps to the\n :data:`DEBUG` config key. It may not behave as expected if set late.\n\n **Do not enable debug mode when deploying in production.**\n\n Default: ``False``\n \"\"\"\n return self.config[\"DEBUG\"]\n\n @debug.setter\n def debug(self, value: bool) -> None:\n self.config[\"DEBUG\"] = value\n\n if self.config[\"TEMPLATES_AUTO_RELOAD\"] is None:\n self.jinja_env.auto_reload = value\n\n def run(\n self,\n host: t.Optional[str] = None,\n port: t.Optional[int] = None,\n debug: t.Optional[bool] = None,\n load_dotenv: bool = True,\n **options: t.Any,\n ) -> None:\n \"\"\"Runs the application on a local development server.\n\n Do not use ``run()`` in a production setting. It is not intended to\n meet security and performance requirements for a production server.\n Instead, see :doc:`/deploying/index` for WSGI server recommendations.\n\n If the :attr:`debug` flag is set the server will automatically reload\n for code changes and show a debugger in case an exception happened.\n\n If you want to run the application in debug mode, but disable the\n code execution on the interactive debugger, you can pass\n ``use_evalex=False`` as parameter. This will keep the debugger's\n traceback screen active, but disable code execution.\n\n It is not recommended to use this function for development with\n automatic reloading as this is badly supported. Instead you should\n be using the :command:`flask` command line script's ``run`` support.\n\n .. admonition:: Keep in Mind\n\n Flask will suppress any server error with a generic error page\n unless it is in debug mode. As such to enable just the\n interactive debugger without the code reloading, you have to\n invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.\n Setting ``use_debugger`` to ``True`` without being in debug mode\n won't catch any exceptions because there won't be any to\n catch.\n\n :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to\n have the server available externally as well. Defaults to\n ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable\n if present.\n :param port: the port of the webserver. Defaults to ``5000`` or the\n port defined in the ``SERVER_NAME`` config variable if present.\n :param debug: if given, enable or disable debug mode. See\n :attr:`debug`.\n :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n files to set environment variables. Will also change the working\n directory to the directory containing the first file found.\n :param options: the options to be forwarded to the underlying Werkzeug\n server. See :func:`werkzeug.serving.run_simple` for more\n information.\n\n .. versionchanged:: 1.0\n If installed, python-dotenv will be used to load environment\n variables from :file:`.env` and :file:`.flaskenv` files.\n\n The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.\n\n Threaded mode is enabled by default.\n\n .. versionchanged:: 0.10\n The default port is now picked from the ``SERVER_NAME``\n variable.\n \"\"\"\n # Ignore this call so that it doesn't start another server if\n # the 'flask run' command is used.\n if os.environ.get(\"FLASK_RUN_FROM_CLI\") == \"true\":\n if not is_running_from_reloader():\n click.secho(\n \" * Ignoring a call to 'app.run()' that would block\"\n \" the current 'flask' CLI command.\\n\"\n \" Only call 'app.run()' in an 'if __name__ ==\"\n ' \"__main__\"\\' guard.',\n fg=\"red\",\n )\n\n return\n\n if get_load_dotenv(load_dotenv):\n cli.load_dotenv()\n\n # if set, env var overrides existing value\n if \"FLASK_DEBUG\" in os.environ:\n self.debug = get_debug_flag()\n\n # debug passed to method overrides all other sources\n if debug is not None:\n self.debug = bool(debug)\n\n server_name = self.config.get(\"SERVER_NAME\")\n sn_host = sn_port = None\n\n if server_name:\n sn_host, _, sn_port = server_name.partition(\":\")\n\n if not host:\n if sn_host:\n host = sn_host\n else:\n host = \"127.0.0.1\"\n\n if port or port == 0:\n port = int(port)\n elif sn_port:\n port = int(sn_port)\n else:\n port = 5000\n\n options.setdefault(\"use_reloader\", self.debug)\n options.setdefault(\"use_debugger\", self.debug)\n options.setdefault(\"threaded\", True)\n\n cli.show_server_banner(self.debug, self.name)\n\n from werkzeug.serving import run_simple\n\n try:\n run_simple(t.cast(str, host), port, self, **options)\n finally:\n # reset the first request information if the development server\n # reset normally. This makes it possible to restart the server\n # without reloader and that stuff from an interactive shell.\n self._got_first_request = False\n\n def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> \"FlaskClient\":\n \"\"\"Creates a test client for this application. For information\n about unit testing head over to :doc:`/testing`.\n\n Note that if you are testing for assertions or exceptions in your\n application code, you must set ``app.testing = True`` in order for the\n exceptions to propagate to the test client. Otherwise, the exception\n will be handled by the application (not visible to the test client) and\n the only indication of an AssertionError or other exception will be a\n 500 status code response to the test client. See the :attr:`testing`\n attribute. For example::\n\n app.testing = True\n client = app.test_client()\n\n The test client can be used in a ``with`` block to defer the closing down\n of the context until the end of the ``with`` block. This is useful if\n you want to access the context locals for testing::\n\n with app.test_client() as c:\n rv = c.get('/?vodka=42')\n assert request.args['vodka'] == '42'\n\n Additionally, you may pass optional keyword arguments that will then\n be passed to the application's :attr:`test_client_class` constructor.\n For example::\n\n from flask.testing import FlaskClient\n\n class CustomClient(FlaskClient):\n def __init__(self, *args, **kwargs):\n self._authentication = kwargs.pop(\"authentication\")\n super(CustomClient,self).__init__( *args, **kwargs)\n\n app.test_client_class = CustomClient\n client = app.test_client(authentication='Basic ....')\n\n See :class:`~flask.testing.FlaskClient` for more information.\n\n .. versionchanged:: 0.4\n added support for ``with`` block usage for the client.\n\n .. versionadded:: 0.7\n The `use_cookies` parameter was added as well as the ability\n to override the client to be used by setting the\n :attr:`test_client_class` attribute.\n\n .. versionchanged:: 0.11\n Added `**kwargs` to support passing additional keyword arguments to\n the constructor of :attr:`test_client_class`.\n \"\"\"\n cls = self.test_client_class\n if cls is None:\n from .testing import FlaskClient as cls\n return cls( # type: ignore\n self, self.response_class, use_cookies=use_cookies, **kwargs\n )\n\n def test_cli_runner(self, **kwargs: t.Any) -> \"FlaskCliRunner\":\n \"\"\"Create a CLI runner for testing CLI commands.\n See :ref:`testing-cli`.\n\n Returns an instance of :attr:`test_cli_runner_class`, by default\n :class:`~flask.testing.FlaskCliRunner`. The Flask app object is\n passed as the first argument.\n\n .. versionadded:: 1.0\n \"\"\"\n cls = self.test_cli_runner_class\n\n if cls is None:\n from .testing import FlaskCliRunner as cls\n\n return cls(self, **kwargs) # type: ignore\n\n @setupmethod\n def register_blueprint(self, blueprint: \"Blueprint\", **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on the application. Keyword\n arguments passed to this method will override the defaults set on the\n blueprint.\n\n Calls the blueprint's :meth:`~flask.Blueprint.register` method after\n recording the blueprint in the application's :attr:`blueprints`.\n\n :param blueprint: The blueprint to register.\n :param url_prefix: Blueprint routes will be prefixed with this.\n :param subdomain: Blueprint routes will match on this subdomain.\n :param url_defaults: Blueprint routes will use these default values for\n view arguments.\n :param options: Additional keyword arguments are passed to\n :class:`~flask.blueprints.BlueprintSetupState`. They can be\n accessed in :meth:`~flask.Blueprint.record` callbacks.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with unique names\n for ``url_for``.\n\n .. versionadded:: 0.7\n \"\"\"\n blueprint.register(self, options)\n\n def iter_blueprints(self) -> t.ValuesView[\"Blueprint\"]:\n \"\"\"Iterates over all blueprints by the order they were registered.\n\n .. versionadded:: 0.11\n \"\"\"\n return self.blueprints.values()\n\n @setupmethod\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[ft.RouteCallable] = None,\n provide_automatic_options: t.Optional[bool] = None,\n **options: t.Any,\n ) -> None:\n if endpoint is None:\n endpoint = _endpoint_from_view_func(view_func) # type: ignore\n options[\"endpoint\"] = endpoint\n methods = options.pop(\"methods\", None)\n\n # if the methods are not given and the view_func object knows its\n # methods we can use that instead. If neither exists, we go with\n # a tuple of only ``GET`` as default.\n if methods is None:\n methods = getattr(view_func, \"methods\", None) or (\"GET\",)\n if isinstance(methods, str):\n raise TypeError(\n \"Allowed methods must be a list of strings, for\"\n ' example: @app.route(..., methods=[\"POST\"])'\n )\n methods = {item.upper() for item in methods}\n\n # Methods that should always be added\n required_methods = set(getattr(view_func, \"required_methods\", ()))\n\n # starting with Flask 0.8 the view_func object can disable and\n # force-enable the automatic options handling.\n if provide_automatic_options is None:\n provide_automatic_options = getattr(\n view_func, \"provide_automatic_options\", None\n )\n\n if provide_automatic_options is None:\n if \"OPTIONS\" not in methods:\n provide_automatic_options = True\n required_methods.add(\"OPTIONS\")\n else:\n provide_automatic_options = False\n\n # Add the required methods now.\n methods |= required_methods\n\n rule = self.url_rule_class(rule, methods=methods, **options)\n rule.provide_automatic_options = provide_automatic_options # type: ignore\n\n self.url_map.add(rule)\n if view_func is not None:\n old_func = self.view_functions.get(endpoint)\n if old_func is not None and old_func != view_func:\n raise AssertionError(\n \"View function mapping is overwriting an existing\"\n f\" endpoint function: {endpoint}\"\n )\n self.view_functions[endpoint] = view_func\n\n @setupmethod\n def template_filter(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_filter], T_template_filter]:\n \"\"\"A decorator that is used to register custom template filter.\n You can specify a name for the filter, otherwise the function\n name will be used. Example::\n\n @app.template_filter()\n def reverse(s):\n return s[::-1]\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_filter) -> T_template_filter:\n self.add_template_filter(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_template_filter(\n self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template filter. Works exactly like the\n :meth:`template_filter` decorator.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.filters[name or f.__name__] = f\n\n @setupmethod\n def template_test(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_test], T_template_test]:\n \"\"\"A decorator that is used to register custom template test.\n You can specify a name for the test, otherwise the function\n name will be used. Example::\n\n @app.template_test()\n def is_prime(n):\n if n == 2:\n return True\n for i in range(2, int(math.ceil(math.sqrt(n))) + 1):\n if n % i == 0:\n return False\n return True\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_test) -> T_template_test:\n self.add_template_test(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_template_test(\n self, f: ft.TemplateTestCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template test. Works exactly like the\n :meth:`template_test` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.tests[name or f.__name__] = f\n\n @setupmethod\n def template_global(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_global], T_template_global]:\n \"\"\"A decorator that is used to register a custom template global function.\n You can specify a name for the global function, otherwise the function\n name will be used. Example::\n\n @app.template_global()\n def double(n):\n return 2 * n\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_global) -> T_template_global:\n self.add_template_global(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_template_global(\n self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a custom template global function. Works exactly like the\n :meth:`template_global` decorator.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global function, otherwise the\n function name will be used.\n \"\"\"\n self.jinja_env.globals[name or f.__name__] = f\n\n @setupmethod\n def teardown_appcontext(self, f: T_teardown) -> T_teardown:\n \"\"\"Registers a function to be called when the application\n context is popped. The application context is typically popped\n after the request context for each request, at the end of CLI\n commands, or after a manually pushed context ends.\n\n .. code-block:: python\n\n with app.app_context():\n ...\n\n When the ``with`` block exits (or ``ctx.pop()`` is called), the\n teardown functions are called just before the app context is\n made inactive. Since a request context typically also manages an\n application context it would also be called when you pop a\n request context.\n\n When a teardown function was called because of an unhandled\n exception it will be passed an error object. If an\n :meth:`errorhandler` is registered, it will handle the exception\n and the teardown will not receive it.\n\n Teardown functions must avoid raising exceptions. If they\n execute code that might fail they must surround that code with a\n ``try``/``except`` block and log any errors.\n\n The return values of teardown functions are ignored.\n\n .. versionadded:: 0.9\n \"\"\"\n self.teardown_appcontext_funcs.append(f)\n return f\n\n @setupmethod\n def shell_context_processor(\n self, f: T_shell_context_processor\n ) -> T_shell_context_processor:\n \"\"\"Registers a shell context processor function.\n\n .. versionadded:: 0.11\n \"\"\"\n self.shell_context_processors.append(f)\n return f\n\n def _find_error_handler(self, e: Exception) -> t.Optional[ft.ErrorHandlerCallable]:\n \"\"\"Return a registered error handler for an exception in this order:\n blueprint handler for a specific code, app handler for a specific code,\n blueprint handler for an exception class, app handler for an exception\n class, or ``None`` if a suitable handler is not found.\n \"\"\"\n exc_class, code = self._get_exc_class_and_code(type(e))\n names = (*request.blueprints, None)\n\n for c in (code, None) if code is not None else (None,):\n for name in names:\n handler_map = self.error_handler_spec[name][c]\n\n if not handler_map:\n continue\n\n for cls in exc_class.__mro__:\n handler = handler_map.get(cls)\n\n if handler is not None:\n return handler\n return None\n\n def handle_http_exception(\n self, e: HTTPException\n ) -> t.Union[HTTPException, ft.ResponseReturnValue]:\n \"\"\"Handles an HTTP exception. By default this will invoke the\n registered error handlers and fall back to returning the\n exception as response.\n\n .. versionchanged:: 1.0.3\n ``RoutingException``, used internally for actions such as\n slash redirects during routing, is not passed to error\n handlers.\n\n .. versionchanged:: 1.0\n Exceptions are looked up by code *and* by MRO, so\n ``HTTPException`` subclasses can be handled with a catch-all\n handler for the base ``HTTPException``.\n\n .. versionadded:: 0.3\n \"\"\"\n # Proxy exceptions don't have error codes. We want to always return\n # those unchanged as errors\n if e.code is None:\n return e\n\n # RoutingExceptions are used internally to trigger routing\n # actions, such as slash redirects raising RequestRedirect. They\n # are not raised or handled in user code.\n if isinstance(e, RoutingException):\n return e\n\n handler = self._find_error_handler(e)\n if handler is None:\n return e\n return self.ensure_sync(handler)(e)\n\n def trap_http_exception(self, e: Exception) -> bool:\n \"\"\"Checks if an HTTP exception should be trapped or not. By default\n this will return ``False`` for all exceptions except for a bad request\n key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It\n also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.\n\n This is called for all HTTP exceptions raised by a view function.\n If it returns ``True`` for any exception the error handler for this\n exception is not called and it shows up as regular exception in the\n traceback. This is helpful for debugging implicitly raised HTTP\n exceptions.\n\n .. versionchanged:: 1.0\n Bad request errors are not trapped by default in debug mode.\n\n .. versionadded:: 0.8\n \"\"\"\n if self.config[\"TRAP_HTTP_EXCEPTIONS\"]:\n return True\n\n trap_bad_request = self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n\n # if unset, trap key errors in debug mode\n if (\n trap_bad_request is None\n and self.debug\n and isinstance(e, BadRequestKeyError)\n ):\n return True\n\n if trap_bad_request:\n return isinstance(e, BadRequest)\n\n return False\n\n def handle_user_exception(\n self, e: Exception\n ) -> t.Union[HTTPException, ft.ResponseReturnValue]:\n \"\"\"This method is called whenever an exception occurs that\n should be handled. A special case is :class:`~werkzeug\n .exceptions.HTTPException` which is forwarded to the\n :meth:`handle_http_exception` method. This function will either\n return a response value or reraise the exception with the same\n traceback.\n\n .. versionchanged:: 1.0\n Key errors raised from request data like ``form`` show the\n bad key in debug mode rather than a generic bad request\n message.\n\n .. versionadded:: 0.7\n \"\"\"\n if isinstance(e, BadRequestKeyError) and (\n self.debug or self.config[\"TRAP_BAD_REQUEST_ERRORS\"]\n ):\n e.show_exception = True\n\n if isinstance(e, HTTPException) and not self.trap_http_exception(e):\n return self.handle_http_exception(e)\n\n handler = self._find_error_handler(e)\n\n if handler is None:\n raise\n\n return self.ensure_sync(handler)(e)\n\n def handle_exception(self, e: Exception) -> Response:\n \"\"\"Handle an exception that did not have an error handler\n associated with it, or that was raised from an error handler.\n This always causes a 500 ``InternalServerError``.\n\n Always sends the :data:`got_request_exception` signal.\n\n If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug\n mode, the error will be re-raised so that the debugger can\n display it. Otherwise, the original exception is logged, and\n an :exc:`~werkzeug.exceptions.InternalServerError` is returned.\n\n If an error handler is registered for ``InternalServerError`` or\n ``500``, it will be used. For consistency, the handler will\n always receive the ``InternalServerError``. The original\n unhandled exception is available as ``e.original_exception``.\n\n .. versionchanged:: 1.1.0\n Always passes the ``InternalServerError`` instance to the\n handler, setting ``original_exception`` to the unhandled\n error.\n\n .. versionchanged:: 1.1.0\n ``after_request`` functions and other finalization is done\n even for the default 500 response when there is no handler.\n\n .. versionadded:: 0.3\n \"\"\"\n exc_info = sys.exc_info()\n got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)\n propagate = self.config[\"PROPAGATE_EXCEPTIONS\"]\n\n if propagate is None:\n propagate = self.testing or self.debug\n\n if propagate:\n # Re-raise if called with an active exception, otherwise\n # raise the passed in exception.\n if exc_info[1] is e:\n raise\n\n raise e\n\n self.log_exception(exc_info)\n server_error: t.Union[InternalServerError, ft.ResponseReturnValue]\n server_error = InternalServerError(original_exception=e)\n handler = self._find_error_handler(server_error)\n\n if handler is not None:\n server_error = self.ensure_sync(handler)(server_error)\n\n return self.finalize_request(server_error, from_error_handler=True)\n\n def log_exception(\n self,\n exc_info: t.Union[\n t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]\n ],\n ) -> None:\n \"\"\"Logs an exception. This is called by :meth:`handle_exception`\n if debugging is disabled and right before the handler is called.\n The default implementation logs the exception as error on the\n :attr:`logger`.\n\n .. versionadded:: 0.8\n \"\"\"\n self.logger.error(\n f\"Exception on {request.path} [{request.method}]\", exc_info=exc_info\n )\n\n def raise_routing_exception(self, request: Request) -> \"te.NoReturn\":\n \"\"\"Intercept routing exceptions and possibly do something else.\n\n In debug mode, intercept a routing redirect and replace it with\n an error if the body will be discarded.\n\n With modern Werkzeug this shouldn't occur, since it now uses a\n 308 status which tells the browser to resend the method and\n body.\n\n .. versionchanged:: 2.1\n Don't intercept 307 and 308 redirects.\n\n :meta private:\n :internal:\n \"\"\"\n if (\n not self.debug\n or not isinstance(request.routing_exception, RequestRedirect)\n or request.routing_exception.code in {307, 308}\n or request.method in {\"GET\", \"HEAD\", \"OPTIONS\"}\n ):\n raise request.routing_exception # type: ignore\n\n from .debughelpers import FormDataRoutingRedirect\n\n raise FormDataRoutingRedirect(request)\n\n def dispatch_request(self) -> ft.ResponseReturnValue:\n \"\"\"Does the request dispatching. Matches the URL and returns the\n return value of the view or error handler. This does not have to\n be a response object. In order to convert the return value to a\n proper response object, call :func:`make_response`.\n\n .. versionchanged:: 0.7\n This no longer does the exception handling, this code was\n moved to the new :meth:`full_dispatch_request`.\n \"\"\"\n req = request_ctx.request\n if req.routing_exception is not None:\n self.raise_routing_exception(req)\n rule: Rule = req.url_rule # type: ignore[assignment]\n # if we provide automatic options for this URL and the\n # request came with the OPTIONS method, reply automatically\n if (\n getattr(rule, \"provide_automatic_options\", False)\n and req.method == \"OPTIONS\"\n ):\n return self.make_default_options_response()\n # otherwise dispatch to the handler for that endpoint\n view_args: t.Dict[str, t.Any] = req.view_args # type: ignore[assignment]\n return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)\n\n def full_dispatch_request(self) -> Response:\n \"\"\"Dispatches the request and on top of that performs request\n pre and postprocessing as well as HTTP exception catching and\n error handling.\n\n .. versionadded:: 0.7\n \"\"\"\n self._got_first_request = True\n\n try:\n request_started.send(self, _async_wrapper=self.ensure_sync)\n rv = self.preprocess_request()\n if rv is None:\n rv = self.dispatch_request()\n except Exception as e:\n rv = self.handle_user_exception(e)\n return self.finalize_request(rv)\n\n def finalize_request(\n self,\n rv: t.Union[ft.ResponseReturnValue, HTTPException],\n from_error_handler: bool = False,\n ) -> Response:\n \"\"\"Given the return value from a view function this finalizes\n the request by converting it into a response and invoking the\n postprocessing functions. This is invoked for both normal\n request dispatching as well as error handlers.\n\n Because this means that it might be called as a result of a\n failure a special safe mode is available which can be enabled\n with the `from_error_handler` flag. If enabled, failures in\n response processing will be logged and otherwise ignored.\n\n :internal:\n \"\"\"\n response = self.make_response(rv)\n try:\n response = self.process_response(response)\n request_finished.send(\n self, _async_wrapper=self.ensure_sync, response=response\n )\n except Exception:\n if not from_error_handler:\n raise\n self.logger.exception(\n \"Request finalizing failed with an error while handling an error\"\n )\n return response\n\n def make_default_options_response(self) -> Response:\n \"\"\"This method is called to create the default ``OPTIONS`` response.\n This can be changed through subclassing to change the default\n behavior of ``OPTIONS`` responses.\n\n .. versionadded:: 0.7\n \"\"\"\n adapter = request_ctx.url_adapter\n methods = adapter.allowed_methods() # type: ignore[union-attr]\n rv = self.response_class()\n rv.allow.update(methods)\n return rv\n\n def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:\n \"\"\"This is called to figure out if an error should be ignored\n or not as far as the teardown system is concerned. If this\n function returns ``True`` then the teardown handlers will not be\n passed the error.\n\n .. versionadded:: 0.10\n \"\"\"\n return False\n\n def ensure_sync(self, func: t.Callable) -> t.Callable:\n \"\"\"Ensure that the function is synchronous for WSGI workers.\n Plain ``def`` functions are returned as-is. ``async def``\n functions are wrapped to run and wait for the response.\n\n Override this method to change how the app runs async views.\n\n .. versionadded:: 2.0\n \"\"\"\n if iscoroutinefunction(func):\n return self.async_to_sync(func)\n\n return func\n\n def async_to_sync(\n self, func: t.Callable[..., t.Coroutine]\n ) -> t.Callable[..., t.Any]:\n \"\"\"Return a sync function that will run the coroutine function.\n\n .. code-block:: python\n\n result = app.async_to_sync(func)(*args, **kwargs)\n\n Override this method to change how the app converts async code\n to be synchronously callable.\n\n .. versionadded:: 2.0\n \"\"\"\n try:\n from asgiref.sync import async_to_sync as asgiref_async_to_sync\n except ImportError:\n raise RuntimeError(\n \"Install Flask with the 'async' extra in order to use async views.\"\n ) from None\n\n return asgiref_async_to_sync(func)\n\n def url_for(\n self,\n endpoint: str,\n *,\n _anchor: t.Optional[str] = None,\n _method: t.Optional[str] = None,\n _scheme: t.Optional[str] = None,\n _external: t.Optional[bool] = None,\n **values: t.Any,\n ) -> str:\n \"\"\"Generate a URL to the given endpoint with the given values.\n\n This is called by :func:`flask.url_for`, and can be called\n directly as well.\n\n An *endpoint* is the name of a URL rule, usually added with\n :meth:`@app.route() `, and usually the same name as the\n view function. A route defined in a :class:`~flask.Blueprint`\n will prepend the blueprint's name separated by a ``.`` to the\n endpoint.\n\n In some cases, such as email messages, you want URLs to include\n the scheme and domain, like ``https://example.com/hello``. When\n not in an active request, URLs will be external by default, but\n this requires setting :data:`SERVER_NAME` so Flask knows what\n domain to use. :data:`APPLICATION_ROOT` and\n :data:`PREFERRED_URL_SCHEME` should also be configured as\n needed. This config is only used when not in an active request.\n\n Functions can be decorated with :meth:`url_defaults` to modify\n keyword arguments before the URL is built.\n\n If building fails for some reason, such as an unknown endpoint\n or incorrect values, the app's :meth:`handle_url_build_error`\n method is called. If that returns a string, that is returned,\n otherwise a :exc:`~werkzeug.routing.BuildError` is raised.\n\n :param endpoint: The endpoint name associated with the URL to\n generate. If this starts with a ``.``, the current blueprint\n name (if any) will be used.\n :param _anchor: If given, append this as ``#anchor`` to the URL.\n :param _method: If given, generate the URL associated with this\n method for the endpoint.\n :param _scheme: If given, the URL will have this scheme if it\n is external.\n :param _external: If given, prefer the URL to be internal\n (False) or require it to be external (True). External URLs\n include the scheme and domain. When not in an active\n request, URLs are external by default.\n :param values: Values to use for the variable parts of the URL\n rule. Unknown keys are appended as query string arguments,\n like ``?a=b&c=d``.\n\n .. versionadded:: 2.2\n Moved from ``flask.url_for``, which calls this method.\n \"\"\"\n req_ctx = _cv_request.get(None)\n\n if req_ctx is not None:\n url_adapter = req_ctx.url_adapter\n blueprint_name = req_ctx.request.blueprint\n\n # If the endpoint starts with \".\" and the request matches a\n # blueprint, the endpoint is relative to the blueprint.\n if endpoint[:1] == \".\":\n if blueprint_name is not None:\n endpoint = f\"{blueprint_name}{endpoint}\"\n else:\n endpoint = endpoint[1:]\n\n # When in a request, generate a URL without scheme and\n # domain by default, unless a scheme is given.\n if _external is None:\n _external = _scheme is not None\n else:\n app_ctx = _cv_app.get(None)\n\n # If called by helpers.url_for, an app context is active,\n # use its url_adapter. Otherwise, app.url_for was called\n # directly, build an adapter.\n if app_ctx is not None:\n url_adapter = app_ctx.url_adapter\n else:\n url_adapter = self.create_url_adapter(None)\n\n if url_adapter is None:\n raise RuntimeError(\n \"Unable to build URLs outside an active request\"\n \" without 'SERVER_NAME' configured. Also configure\"\n \" 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as\"\n \" needed.\"\n )\n\n # When outside a request, generate a URL with scheme and\n # domain by default.\n if _external is None:\n _external = True\n\n # It is an error to set _scheme when _external=False, in order\n # to avoid accidental insecure URLs.\n if _scheme is not None and not _external:\n raise ValueError(\"When specifying '_scheme', '_external' must be True.\")\n\n self.inject_url_defaults(endpoint, values)\n\n try:\n rv = url_adapter.build( # type: ignore[union-attr]\n endpoint,\n values,\n method=_method,\n url_scheme=_scheme,\n force_external=_external,\n )\n except BuildError as error:\n values.update(\n _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external\n )\n return self.handle_url_build_error(error, endpoint, values)\n\n if _anchor is not None:\n _anchor = _url_quote(_anchor, safe=\"%!#$&'()*+,/:;=?@\")\n rv = f\"{rv}#{_anchor}\"\n\n return rv\n\n def redirect(self, location: str, code: int = 302) -> BaseResponse:\n \"\"\"Create a redirect response object.\n\n This is called by :func:`flask.redirect`, and can be called\n directly as well.\n\n :param location: The URL to redirect to.\n :param code: The status code for the redirect.\n\n .. versionadded:: 2.2\n Moved from ``flask.redirect``, which calls this method.\n \"\"\"\n return _wz_redirect(location, code=code, Response=self.response_class)\n\n def make_response(self, rv: ft.ResponseReturnValue) -> Response:\n \"\"\"Convert the return value from a view function to an instance of\n :attr:`response_class`.\n\n :param rv: the return value from the view function. The view function\n must return a response. Returning ``None``, or the view ending\n without returning, is not allowed. The following types are allowed\n for ``view_rv``:\n\n ``str``\n A response object is created with the string encoded to UTF-8\n as the body.\n\n ``bytes``\n A response object is created with the bytes as the body.\n\n ``dict``\n A dictionary that will be jsonify'd before being returned.\n\n ``list``\n A list that will be jsonify'd before being returned.\n\n ``generator`` or ``iterator``\n A generator that returns ``str`` or ``bytes`` to be\n streamed as the response.\n\n ``tuple``\n Either ``(body, status, headers)``, ``(body, status)``, or\n ``(body, headers)``, where ``body`` is any of the other types\n allowed here, ``status`` is a string or an integer, and\n ``headers`` is a dictionary or a list of ``(key, value)``\n tuples. If ``body`` is a :attr:`response_class` instance,\n ``status`` overwrites the exiting value and ``headers`` are\n extended.\n\n :attr:`response_class`\n The object is returned unchanged.\n\n other :class:`~werkzeug.wrappers.Response` class\n The object is coerced to :attr:`response_class`.\n\n :func:`callable`\n The function is called as a WSGI application. The result is\n used to create a response object.\n\n .. versionchanged:: 2.2\n A generator will be converted to a streaming response.\n A list will be converted to a JSON response.\n\n .. versionchanged:: 1.1\n A dict will be converted to a JSON response.\n\n .. versionchanged:: 0.9\n Previously a tuple was interpreted as the arguments for the\n response object.\n \"\"\"\n\n status = headers = None\n\n # unpack tuple returns\n if isinstance(rv, tuple):\n len_rv = len(rv)\n\n # a 3-tuple is unpacked directly\n if len_rv == 3:\n rv, status, headers = rv # type: ignore[misc]\n # decide if a 2-tuple has status or headers\n elif len_rv == 2:\n if isinstance(rv[1], (Headers, dict, tuple, list)):\n rv, headers = rv\n else:\n rv, status = rv # type: ignore[assignment,misc]\n # other sized tuples are not allowed\n else:\n raise TypeError(\n \"The view function did not return a valid response tuple.\"\n \" The tuple must have the form (body, status, headers),\"\n \" (body, status), or (body, headers).\"\n )\n\n # the body must not be None\n if rv is None:\n raise TypeError(\n f\"The view function for {request.endpoint!r} did not\"\n \" return a valid response. The function either returned\"\n \" None or ended without a return statement.\"\n )\n\n # make sure the body is an instance of the response class\n if not isinstance(rv, self.response_class):\n if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):\n # let the response class set the status and headers instead of\n # waiting to do it manually, so that the class can handle any\n # special logic\n rv = self.response_class(\n rv,\n status=status,\n headers=headers, # type: ignore[arg-type]\n )\n status = headers = None\n elif isinstance(rv, (dict, list)):\n rv = self.json.response(rv)\n elif isinstance(rv, BaseResponse) or callable(rv):\n # evaluate a WSGI callable, or coerce a different response\n # class to the correct type\n try:\n rv = self.response_class.force_type(\n rv, request.environ # type: ignore[arg-type]\n )\n except TypeError as e:\n raise TypeError(\n f\"{e}\\nThe view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, list, tuple with headers or status,\"\n \" Response instance, or WSGI callable, but it\"\n f\" was a {type(rv).__name__}.\"\n ).with_traceback(sys.exc_info()[2]) from None\n else:\n raise TypeError(\n \"The view function did not return a valid\"\n \" response. The return type must be a string,\"\n \" dict, list, tuple with headers or status,\"\n \" Response instance, or WSGI callable, but it was a\"\n f\" {type(rv).__name__}.\"\n )\n\n rv = t.cast(Response, rv)\n # prefer the status if it was provided\n if status is not None:\n if isinstance(status, (str, bytes, bytearray)):\n rv.status = status\n else:\n rv.status_code = status\n\n # extend existing headers with provided headers\n if headers:\n rv.headers.update(headers) # type: ignore[arg-type]\n\n return rv\n\n def create_url_adapter(\n self, request: t.Optional[Request]\n ) -> t.Optional[MapAdapter]:\n \"\"\"Creates a URL adapter for the given request. The URL adapter\n is created at a point where the request context is not yet set\n up so the request is passed explicitly.\n\n .. versionadded:: 0.6\n\n .. versionchanged:: 0.9\n This can now also be called without a request object when the\n URL adapter is created for the application context.\n\n .. versionchanged:: 1.0\n :data:`SERVER_NAME` no longer implicitly enables subdomain\n matching. Use :attr:`subdomain_matching` instead.\n \"\"\"\n if request is not None:\n # If subdomain matching is disabled (the default), use the\n # default subdomain in all cases. This should be the default\n # in Werkzeug but it currently does not have that feature.\n if not self.subdomain_matching:\n subdomain = self.url_map.default_subdomain or None\n else:\n subdomain = None\n\n return self.url_map.bind_to_environ(\n request.environ,\n server_name=self.config[\"SERVER_NAME\"],\n subdomain=subdomain,\n )\n # We need at the very least the server name to be set for this\n # to work.\n if self.config[\"SERVER_NAME\"] is not None:\n return self.url_map.bind(\n self.config[\"SERVER_NAME\"],\n script_name=self.config[\"APPLICATION_ROOT\"],\n url_scheme=self.config[\"PREFERRED_URL_SCHEME\"],\n )\n\n return None\n\n def inject_url_defaults(self, endpoint: str, values: dict) -> None:\n \"\"\"Injects the URL defaults for the given endpoint directly into\n the values dictionary passed. This is used internally and\n automatically called on URL building.\n\n .. versionadded:: 0.7\n \"\"\"\n names: t.Iterable[t.Optional[str]] = (None,)\n\n # url_for may be called outside a request context, parse the\n # passed endpoint instead of using request.blueprints.\n if \".\" in endpoint:\n names = chain(\n names, reversed(_split_blueprint_path(endpoint.rpartition(\".\")[0]))\n )\n\n for name in names:\n if name in self.url_default_functions:\n for func in self.url_default_functions[name]:\n func(endpoint, values)\n\n def handle_url_build_error(\n self, error: BuildError, endpoint: str, values: t.Dict[str, t.Any]\n ) -> str:\n \"\"\"Called by :meth:`.url_for` if a\n :exc:`~werkzeug.routing.BuildError` was raised. If this returns\n a value, it will be returned by ``url_for``, otherwise the error\n will be re-raised.\n\n Each function in :attr:`url_build_error_handlers` is called with\n ``error``, ``endpoint`` and ``values``. If a function returns\n ``None`` or raises a ``BuildError``, it is skipped. Otherwise,\n its return value is returned by ``url_for``.\n\n :param error: The active ``BuildError`` being handled.\n :param endpoint: The endpoint being built.\n :param values: The keyword arguments passed to ``url_for``.\n \"\"\"\n for handler in self.url_build_error_handlers:\n try:\n rv = handler(error, endpoint, values)\n except BuildError as e:\n # make error available outside except block\n error = e\n else:\n if rv is not None:\n return rv\n\n # Re-raise if called with an active exception, otherwise raise\n # the passed in exception.\n if error is sys.exc_info()[1]:\n raise\n\n raise error\n\n def preprocess_request(self) -> t.Optional[ft.ResponseReturnValue]:\n \"\"\"Called before the request is dispatched. Calls\n :attr:`url_value_preprocessors` registered with the app and the\n current blueprint (if any). Then calls :attr:`before_request_funcs`\n registered with the app and the blueprint.\n\n If any :meth:`before_request` handler returns a non-None value, the\n value is handled as if it was the return value from the view, and\n further request handling is stopped.\n \"\"\"\n names = (None, *reversed(request.blueprints))\n\n for name in names:\n if name in self.url_value_preprocessors:\n for url_func in self.url_value_preprocessors[name]:\n url_func(request.endpoint, request.view_args)\n\n for name in names:\n if name in self.before_request_funcs:\n for before_func in self.before_request_funcs[name]:\n rv = self.ensure_sync(before_func)()\n\n if rv is not None:\n return rv\n\n return None\n\n def process_response(self, response: Response) -> Response:\n \"\"\"Can be overridden in order to modify the response object\n before it's sent to the WSGI server. By default this will\n call all the :meth:`after_request` decorated functions.\n\n .. versionchanged:: 0.5\n As of Flask 0.5 the functions registered for after request\n execution are called in reverse order of registration.\n\n :param response: a :attr:`response_class` object.\n :return: a new response object or the same, has to be an\n instance of :attr:`response_class`.\n \"\"\"\n ctx = request_ctx._get_current_object() # type: ignore[attr-defined]\n\n for func in ctx._after_request_functions:\n response = self.ensure_sync(func)(response)\n\n for name in chain(request.blueprints, (None,)):\n if name in self.after_request_funcs:\n for func in reversed(self.after_request_funcs[name]):\n response = self.ensure_sync(func)(response)\n\n if not self.session_interface.is_null_session(ctx.session):\n self.session_interface.save_session(self, ctx.session, response)\n\n return response\n\n def do_teardown_request(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None:\n \"\"\"Called after the request is dispatched and the response is\n returned, right before the request context is popped.\n\n This calls all functions decorated with\n :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`\n if a blueprint handled the request. Finally, the\n :data:`request_tearing_down` signal is sent.\n\n This is called by\n :meth:`RequestContext.pop() `,\n which may be delayed during testing to maintain access to\n resources.\n\n :param exc: An unhandled exception raised while dispatching the\n request. Detected from the current exception information if\n not passed. Passed to each teardown function.\n\n .. versionchanged:: 0.9\n Added the ``exc`` argument.\n \"\"\"\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n\n for name in chain(request.blueprints, (None,)):\n if name in self.teardown_request_funcs:\n for func in reversed(self.teardown_request_funcs[name]):\n self.ensure_sync(func)(exc)\n\n request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n def do_teardown_appcontext(\n self, exc: t.Optional[BaseException] = _sentinel # type: ignore\n ) -> None:\n \"\"\"Called right before the application context is popped.\n\n When handling a request, the application context is popped\n after the request context. See :meth:`do_teardown_request`.\n\n This calls all functions decorated with\n :meth:`teardown_appcontext`. Then the\n :data:`appcontext_tearing_down` signal is sent.\n\n This is called by\n :meth:`AppContext.pop() `.\n\n .. versionadded:: 0.9\n \"\"\"\n if exc is _sentinel:\n exc = sys.exc_info()[1]\n\n for func in reversed(self.teardown_appcontext_funcs):\n self.ensure_sync(func)(exc)\n\n appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)\n\n def app_context(self) -> AppContext:\n \"\"\"Create an :class:`~flask.ctx.AppContext`. Use as a ``with``\n block to push the context, which will make :data:`current_app`\n point at this application.\n\n An application context is automatically pushed by\n :meth:`RequestContext.push() `\n when handling a request, and when running a CLI command. Use\n this to manually create a context outside of these situations.\n\n ::\n\n with app.app_context():\n init_db()\n\n See :doc:`/appcontext`.\n\n .. versionadded:: 0.9\n \"\"\"\n return AppContext(self)\n\n def request_context(self, environ: dict) -> RequestContext:\n \"\"\"Create a :class:`~flask.ctx.RequestContext` representing a\n WSGI environment. Use a ``with`` block to push the context,\n which will make :data:`request` point at this request.\n\n See :doc:`/reqcontext`.\n\n Typically you should not call this from your own code. A request\n context is automatically pushed by the :meth:`wsgi_app` when\n handling a request. Use :meth:`test_request_context` to create\n an environment and context instead of this method.\n\n :param environ: a WSGI environment\n \"\"\"\n return RequestContext(self, environ)\n\n def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:\n \"\"\"Create a :class:`~flask.ctx.RequestContext` for a WSGI\n environment created from the given values. This is mostly useful\n during testing, where you may want to run a function that uses\n request data without dispatching a full request.\n\n See :doc:`/reqcontext`.\n\n Use a ``with`` block to push the context, which will make\n :data:`request` point at the request for the created\n environment. ::\n\n with app.test_request_context(...):\n generate_report()\n\n When using the shell, it may be easier to push and pop the\n context manually to avoid indentation. ::\n\n ctx = app.test_request_context(...)\n ctx.push()\n ...\n ctx.pop()\n\n Takes the same arguments as Werkzeug's\n :class:`~werkzeug.test.EnvironBuilder`, with some defaults from\n the application. See the linked Werkzeug docs for most of the\n available arguments. Flask-specific behavior is listed here.\n\n :param path: URL path being requested.\n :param base_url: Base URL where the app is being served, which\n ``path`` is relative to. If not given, built from\n :data:`PREFERRED_URL_SCHEME`, ``subdomain``,\n :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.\n :param subdomain: Subdomain name to append to\n :data:`SERVER_NAME`.\n :param url_scheme: Scheme to use instead of\n :data:`PREFERRED_URL_SCHEME`.\n :param data: The request body, either as a string or a dict of\n form keys and values.\n :param json: If given, this is serialized as JSON and passed as\n ``data``. Also defaults ``content_type`` to\n ``application/json``.\n :param args: other positional arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n :param kwargs: other keyword arguments passed to\n :class:`~werkzeug.test.EnvironBuilder`.\n \"\"\"\n from .testing import EnvironBuilder\n\n builder = EnvironBuilder(self, *args, **kwargs)\n\n try:\n return self.request_context(builder.get_environ())\n finally:\n builder.close()\n\n def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:\n \"\"\"The actual WSGI application. This is not implemented in\n :meth:`__call__` so that middlewares can be applied without\n losing a reference to the app object. Instead of doing this::\n\n app = MyMiddleware(app)\n\n It's a better idea to do this instead::\n\n app.wsgi_app = MyMiddleware(app.wsgi_app)\n\n Then you still have the original application object around and\n can continue to call methods on it.\n\n .. versionchanged:: 0.7\n Teardown events for the request and app contexts are called\n even if an unhandled error occurs. Other events may not be\n called depending on when an error occurs during dispatch.\n See :ref:`callbacks-and-errors`.\n\n :param environ: A WSGI environment.\n :param start_response: A callable accepting a status code,\n a list of headers, and an optional exception context to\n start the response.\n \"\"\"\n ctx = self.request_context(environ)\n error: t.Optional[BaseException] = None\n try:\n try:\n ctx.push()\n response = self.full_dispatch_request()\n except Exception as e:\n error = e\n response = self.handle_exception(e)\n except: # noqa: B001\n error = sys.exc_info()[1]\n raise\n return response(environ, start_response)\n finally:\n if \"werkzeug.debug.preserve_context\" in environ:\n environ[\"werkzeug.debug.preserve_context\"](_cv_app.get())\n environ[\"werkzeug.debug.preserve_context\"](_cv_request.get())\n\n if error is not None and self.should_ignore_error(error):\n error = None\n\n ctx.pop(error)\n\n def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:\n \"\"\"The WSGI server calls the Flask application object as the\n WSGI application. This calls :meth:`wsgi_app`, which can be\n wrapped to apply middleware.\n \"\"\"\n return self.wsgi_app(environ, start_response)"},{"col":0,"comment":"null","endLoc":18,"header":"@bp.get(\"/result/\")\ndef result(id","id":120,"name":"result","nodeType":"Function","startLoc":10,"text":"@bp.get(\"/result/\")\ndef result(id: str) -> dict[str, object]:\n result = AsyncResult(id)\n ready = result.ready()\n return {\n \"ready\": ready,\n \"successful\": result.successful() if ready else None,\n \"value\": result.get() if ready else result.result,\n }"},{"className":"Scaffold","col":0,"comment":"Common behavior shared between :class:`~flask.Flask` and\n :class:`~flask.blueprints.Blueprint`.\n\n :param import_name: The import name of the module where this object\n is defined. Usually :attr:`__name__` should be used.\n :param static_folder: Path to a folder of static files to serve.\n If this is set, a static route will be added.\n :param static_url_path: URL prefix for the static route.\n :param template_folder: Path to a folder containing template files.\n for rendering. If this is set, a Jinja loader will be added.\n :param root_path: The path that static, template, and resource files\n are relative to. Typically not set, it is discovered based on\n the ``import_name``.\n\n .. versionadded:: 2.0\n ","endLoc":770,"id":121,"nodeType":"Class","startLoc":54,"text":"class Scaffold:\n \"\"\"Common behavior shared between :class:`~flask.Flask` and\n :class:`~flask.blueprints.Blueprint`.\n\n :param import_name: The import name of the module where this object\n is defined. Usually :attr:`__name__` should be used.\n :param static_folder: Path to a folder of static files to serve.\n If this is set, a static route will be added.\n :param static_url_path: URL prefix for the static route.\n :param template_folder: Path to a folder containing template files.\n for rendering. If this is set, a Jinja loader will be added.\n :param root_path: The path that static, template, and resource files\n are relative to. Typically not set, it is discovered based on\n the ``import_name``.\n\n .. versionadded:: 2.0\n \"\"\"\n\n name: str\n _static_folder: t.Optional[str] = None\n _static_url_path: t.Optional[str] = None\n\n def __init__(\n self,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n root_path: t.Optional[str] = None,\n ):\n #: The name of the package or module that this object belongs\n #: to. Do not change this once it is set by the constructor.\n self.import_name = import_name\n\n self.static_folder = static_folder # type: ignore\n self.static_url_path = static_url_path\n\n #: The path to the templates folder, relative to\n #: :attr:`root_path`, to add to the template loader. ``None`` if\n #: templates should not be added.\n self.template_folder = template_folder\n\n if root_path is None:\n root_path = get_root_path(self.import_name)\n\n #: Absolute path to the package on the filesystem. Used to look\n #: up resources contained in the package.\n self.root_path = root_path\n\n #: The Click command group for registering CLI commands for this\n #: object. The commands are available from the ``flask`` command\n #: once the application has been discovered and blueprints have\n #: been registered.\n self.cli = AppGroup()\n\n #: A dictionary mapping endpoint names to view functions.\n #:\n #: To register a view function, use the :meth:`route` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.view_functions: t.Dict[str, t.Callable] = {}\n\n #: A data structure of registered error handlers, in the format\n #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n #: the name of a blueprint the handlers are active for, or\n #: ``None`` for all requests. The ``code`` key is the HTTP\n #: status code for ``HTTPException``, or ``None`` for\n #: other exceptions. The innermost dictionary maps exception\n #: classes to handler functions.\n #:\n #: To register an error handler, use the :meth:`errorhandler`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.error_handler_spec: t.Dict[\n ft.AppOrBlueprintKey,\n t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ft.ErrorHandlerCallable]],\n ] = defaultdict(lambda: defaultdict(dict))\n\n #: A data structure of functions to call at the beginning of\n #: each request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`before_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.before_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.BeforeRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`after_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.after_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.AfterRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request even if an exception is raised, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`teardown_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.teardown_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.TeardownCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call to pass extra context\n #: values when rendering templates, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`context_processor`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.template_context_processors: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.TemplateContextProcessorCallable]\n ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n #: A data structure of functions to call to modify the keyword\n #: arguments passed to the view function, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the\n #: :meth:`url_value_preprocessor` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_value_preprocessors: t.Dict[\n ft.AppOrBlueprintKey,\n t.List[ft.URLValuePreprocessorCallable],\n ] = defaultdict(list)\n\n #: A data structure of functions to call to modify the keyword\n #: arguments when generating URLs, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`url_defaults`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_default_functions: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.URLDefaultCallable]\n ] = defaultdict(list)\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__} {self.name!r}>\"\n\n def _check_setup_finished(self, f_name: str) -> None:\n raise NotImplementedError\n\n @property\n def static_folder(self) -> t.Optional[str]:\n \"\"\"The absolute path to the configured static folder. ``None``\n if no static folder is set.\n \"\"\"\n if self._static_folder is not None:\n return os.path.join(self.root_path, self._static_folder)\n else:\n return None\n\n @static_folder.setter\n def static_folder(self, value: t.Optional[t.Union[str, os.PathLike]]) -> None:\n if value is not None:\n value = os.fspath(value).rstrip(r\"\\/\")\n\n self._static_folder = value\n\n @property\n def has_static_folder(self) -> bool:\n \"\"\"``True`` if :attr:`static_folder` is set.\n\n .. versionadded:: 0.5\n \"\"\"\n return self.static_folder is not None\n\n @property\n def static_url_path(self) -> t.Optional[str]:\n \"\"\"The URL prefix that the static route will be accessible from.\n\n If it was not configured during init, it is derived from\n :attr:`static_folder`.\n \"\"\"\n if self._static_url_path is not None:\n return self._static_url_path\n\n if self.static_folder is not None:\n basename = os.path.basename(self.static_folder)\n return f\"/{basename}\".rstrip(\"/\")\n\n return None\n\n @static_url_path.setter\n def static_url_path(self, value: t.Optional[str]) -> None:\n if value is not None:\n value = value.rstrip(\"/\")\n\n self._static_url_path = value\n\n def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]:\n \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n value for a given file path if it wasn't passed.\n\n By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n the configuration of :data:`~flask.current_app`. This defaults\n to ``None``, which tells the browser to use conditional requests\n instead of a timed cache, which is usually preferable.\n\n .. versionchanged:: 2.0\n The default configuration is ``None`` instead of 12 hours.\n\n .. versionadded:: 0.9\n \"\"\"\n value = current_app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n if value is None:\n return None\n\n if isinstance(value, timedelta):\n return int(value.total_seconds())\n\n return value\n\n def send_static_file(self, filename: str) -> \"Response\":\n \"\"\"The view function used to serve files from\n :attr:`static_folder`. A route is automatically registered for\n this view at :attr:`static_url_path` if :attr:`static_folder` is\n set.\n\n .. versionadded:: 0.5\n \"\"\"\n if not self.has_static_folder:\n raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n # send_file only knows to call get_send_file_max_age on the app,\n # call it here so it works for blueprints too.\n max_age = self.get_send_file_max_age(filename)\n return send_from_directory(\n t.cast(str, self.static_folder), filename, max_age=max_age\n )\n\n @cached_property\n def jinja_loader(self) -> t.Optional[FileSystemLoader]:\n \"\"\"The Jinja loader for this object's templates. By default this\n is a class :class:`jinja2.loaders.FileSystemLoader` to\n :attr:`template_folder` if it is set.\n\n .. versionadded:: 0.5\n \"\"\"\n if self.template_folder is not None:\n return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n else:\n return None\n\n def open_resource(self, resource: str, mode: str = \"rb\") -> t.IO[t.AnyStr]:\n \"\"\"Open a resource file relative to :attr:`root_path` for\n reading.\n\n For example, if the file ``schema.sql`` is next to the file\n ``app.py`` where the ``Flask`` app is defined, it can be opened\n with:\n\n .. code-block:: python\n\n with app.open_resource(\"schema.sql\") as f:\n conn.executescript(f.read())\n\n :param resource: Path to the resource relative to\n :attr:`root_path`.\n :param mode: Open the file in this mode. Only reading is\n supported, valid values are \"r\" (or \"rt\") and \"rb\".\n \"\"\"\n if mode not in {\"r\", \"rt\", \"rb\"}:\n raise ValueError(\"Resources can only be opened for reading.\")\n\n return open(os.path.join(self.root_path, resource), mode)\n\n def _method_route(\n self,\n method: str,\n rule: str,\n options: dict,\n ) -> t.Callable[[T_route], T_route]:\n if \"methods\" in options:\n raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n return self.route(rule, methods=[method], **options)\n\n @setupmethod\n def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"GET\", rule, options)\n\n @setupmethod\n def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"POST\", rule, options)\n\n @setupmethod\n def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PUT\", rule, options)\n\n @setupmethod\n def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"DELETE\", rule, options)\n\n @setupmethod\n def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PATCH\", rule, options)\n\n @setupmethod\n def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Decorate a view function to register it with the given URL\n rule and options. Calls :meth:`add_url_rule`, which has more\n details about the implementation.\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n return \"Hello, World!\"\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n ``OPTIONS`` are added automatically.\n\n :param rule: The URL rule string.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n\n def decorator(f: T_route) -> T_route:\n endpoint = options.pop(\"endpoint\", None)\n self.add_url_rule(rule, endpoint, f, **options)\n return f\n\n return decorator\n\n @setupmethod\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[ft.RouteCallable] = None,\n provide_automatic_options: t.Optional[bool] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Register a rule for routing incoming requests and building\n URLs. The :meth:`route` decorator is a shortcut to call this\n with the ``view_func`` argument. These are equivalent:\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n ...\n\n .. code-block:: python\n\n def index():\n ...\n\n app.add_url_rule(\"/\", view_func=index)\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed. An error\n will be raised if a function has already been registered for the\n endpoint.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n always added automatically, and ``OPTIONS`` is added\n automatically by default.\n\n ``view_func`` does not necessarily need to be passed, but if the\n rule should participate in routing an endpoint name must be\n associated with a view function at some point with the\n :meth:`endpoint` decorator.\n\n .. code-block:: python\n\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n @app.endpoint(\"index\")\n def index():\n ...\n\n If ``view_func`` has a ``required_methods`` attribute, those\n methods are added to the passed and automatic methods. If it\n has a ``provide_automatic_methods`` attribute, it is used as the\n default if the parameter is not passed.\n\n :param rule: The URL rule string.\n :param endpoint: The endpoint name to associate with the rule\n and view function. Used when routing and building URLs.\n Defaults to ``view_func.__name__``.\n :param view_func: The view function to associate with the\n endpoint name.\n :param provide_automatic_options: Add the ``OPTIONS`` method and\n respond to ``OPTIONS`` requests automatically.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n raise NotImplementedError\n\n @setupmethod\n def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n \"\"\"Decorate a view function to register it for the given\n endpoint. Used if a rule is added without a ``view_func`` with\n :meth:`add_url_rule`.\n\n .. code-block:: python\n\n app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n @app.endpoint(\"example\")\n def example():\n ...\n\n :param endpoint: The endpoint name to associate with the view\n function.\n \"\"\"\n\n def decorator(f: F) -> F:\n self.view_functions[endpoint] = f\n return f\n\n return decorator\n\n @setupmethod\n def before_request(self, f: T_before_request) -> T_before_request:\n \"\"\"Register a function to run before each request.\n\n For example, this can be used to open a database connection, or\n to load the logged in user from the session.\n\n .. code-block:: python\n\n @app.before_request\n def load_user():\n if \"user_id\" in session:\n g.user = db.session.get(session[\"user_id\"])\n\n The function will be called without any arguments. If it returns\n a non-``None`` value, the value is handled as if it was the\n return value from the view, and further request handling is\n stopped.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes before every request. When used on a blueprint, this executes before\n every request that the blueprint handles. To register with a blueprint and\n execute before every request, use :meth:`.Blueprint.before_app_request`.\n \"\"\"\n self.before_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def after_request(self, f: T_after_request) -> T_after_request:\n \"\"\"Register a function to run after each request to this object.\n\n The function is called with the response object, and must return\n a response object. This allows the functions to modify or\n replace the response before it is sent.\n\n If a function raises an exception, any remaining\n ``after_request`` functions will not be called. Therefore, this\n should not be used for actions that must execute, such as to\n close resources. Use :meth:`teardown_request` for that.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes after every request. When used on a blueprint, this executes after\n every request that the blueprint handles. To register with a blueprint and\n execute after every request, use :meth:`.Blueprint.after_app_request`.\n \"\"\"\n self.after_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def teardown_request(self, f: T_teardown) -> T_teardown:\n \"\"\"Register a function to be called when the request context is\n popped. Typically this happens at the end of each request, but\n contexts may be pushed manually as well during testing.\n\n .. code-block:: python\n\n with app.test_request_context():\n ...\n\n When the ``with`` block exits (or ``ctx.pop()`` is called), the\n teardown functions are called just before the request context is\n made inactive.\n\n When a teardown function was called because of an unhandled\n exception it will be passed an error object. If an\n :meth:`errorhandler` is registered, it will handle the exception\n and the teardown will not receive it.\n\n Teardown functions must avoid raising exceptions. If they\n execute code that might fail they must surround that code with a\n ``try``/``except`` block and log any errors.\n\n The return values of teardown functions are ignored.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes after every request. When used on a blueprint, this executes after\n every request that the blueprint handles. To register with a blueprint and\n execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n \"\"\"\n self.teardown_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def context_processor(\n self,\n f: T_template_context_processor,\n ) -> T_template_context_processor:\n \"\"\"Registers a template context processor function. These functions run before\n rendering a template. The keys of the returned dict are added as variables\n available in the template.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every rendered template. When used on a blueprint, this is called\n for templates rendered from the blueprint's views. To register with a blueprint\n and affect every template, use :meth:`.Blueprint.app_context_processor`.\n \"\"\"\n self.template_context_processors[None].append(f)\n return f\n\n @setupmethod\n def url_value_preprocessor(\n self,\n f: T_url_value_preprocessor,\n ) -> T_url_value_preprocessor:\n \"\"\"Register a URL value preprocessor function for all view\n functions in the application. These functions will be called before the\n :meth:`before_request` functions.\n\n The function can modify the values captured from the matched url before\n they are passed to the view. For example, this can be used to pop a\n common language code value and place it in ``g`` rather than pass it to\n every view.\n\n The function is passed the endpoint name and values dict. The return\n value is ignored.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every request. When used on a blueprint, this is called for\n requests that the blueprint handles. To register with a blueprint and affect\n every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n \"\"\"\n self.url_value_preprocessors[None].append(f)\n return f\n\n @setupmethod\n def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n \"\"\"Callback function for URL defaults for all view functions of the\n application. It's called with the endpoint and values and should\n update the values passed in place.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every request. When used on a blueprint, this is called for\n requests that the blueprint handles. To register with a blueprint and affect\n every request, use :meth:`.Blueprint.app_url_defaults`.\n \"\"\"\n self.url_default_functions[None].append(f)\n return f\n\n @setupmethod\n def errorhandler(\n self, code_or_exception: t.Union[t.Type[Exception], int]\n ) -> t.Callable[[T_error_handler], T_error_handler]:\n \"\"\"Register a function to handle errors by code or exception class.\n\n A decorator that is used to register a function given an\n error code. Example::\n\n @app.errorhandler(404)\n def page_not_found(error):\n return 'This page does not exist', 404\n\n You can also register handlers for arbitrary exceptions::\n\n @app.errorhandler(DatabaseError)\n def special_exception_handler(error):\n return 'Database connection failed', 500\n\n This is available on both app and blueprint objects. When used on an app, this\n can handle errors from every request. When used on a blueprint, this can handle\n errors from requests that the blueprint handles. To register with a blueprint\n and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n .. versionadded:: 0.7\n Use :meth:`register_error_handler` instead of modifying\n :attr:`error_handler_spec` directly, for application wide error\n handlers.\n\n .. versionadded:: 0.7\n One can now additionally also register custom exception types\n that do not necessarily have to be a subclass of the\n :class:`~werkzeug.exceptions.HTTPException` class.\n\n :param code_or_exception: the code as integer for the handler, or\n an arbitrary exception\n \"\"\"\n\n def decorator(f: T_error_handler) -> T_error_handler:\n self.register_error_handler(code_or_exception, f)\n return f\n\n return decorator\n\n @setupmethod\n def register_error_handler(\n self,\n code_or_exception: t.Union[t.Type[Exception], int],\n f: ft.ErrorHandlerCallable,\n ) -> None:\n \"\"\"Alternative error attach function to the :meth:`errorhandler`\n decorator that is more straightforward to use for non decorator\n usage.\n\n .. versionadded:: 0.7\n \"\"\"\n exc_class, code = self._get_exc_class_and_code(code_or_exception)\n self.error_handler_spec[None][code][exc_class] = f\n\n @staticmethod\n def _get_exc_class_and_code(\n exc_class_or_code: t.Union[t.Type[Exception], int]\n ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:\n \"\"\"Get the exception class being handled. For HTTP status codes\n or ``HTTPException`` subclasses, return both the exception and\n status code.\n\n :param exc_class_or_code: Any exception class, or an HTTP status\n code as an integer.\n \"\"\"\n exc_class: t.Type[Exception]\n\n if isinstance(exc_class_or_code, int):\n try:\n exc_class = default_exceptions[exc_class_or_code]\n except KeyError:\n raise ValueError(\n f\"'{exc_class_or_code}' is not a recognized HTTP\"\n \" error code. Use a subclass of HTTPException with\"\n \" that code instead.\"\n ) from None\n else:\n exc_class = exc_class_or_code\n\n if isinstance(exc_class, Exception):\n raise TypeError(\n f\"{exc_class!r} is an instance, not a class. Handlers\"\n \" can only be registered for Exception classes or HTTP\"\n \" error codes.\"\n )\n\n if not issubclass(exc_class, Exception):\n raise ValueError(\n f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n \" Handlers can only be registered for Exception classes\"\n \" or HTTP error codes.\"\n )\n\n if issubclass(exc_class, HTTPException):\n return exc_class, exc_class.code\n else:\n return exc_class, None"},{"col":4,"comment":"null","endLoc":222,"header":"def __init__(\n self,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n root_path: t.Optional[str] = None,\n )","id":122,"name":"__init__","nodeType":"Function","startLoc":76,"text":"def __init__(\n self,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n root_path: t.Optional[str] = None,\n ):\n #: The name of the package or module that this object belongs\n #: to. Do not change this once it is set by the constructor.\n self.import_name = import_name\n\n self.static_folder = static_folder # type: ignore\n self.static_url_path = static_url_path\n\n #: The path to the templates folder, relative to\n #: :attr:`root_path`, to add to the template loader. ``None`` if\n #: templates should not be added.\n self.template_folder = template_folder\n\n if root_path is None:\n root_path = get_root_path(self.import_name)\n\n #: Absolute path to the package on the filesystem. Used to look\n #: up resources contained in the package.\n self.root_path = root_path\n\n #: The Click command group for registering CLI commands for this\n #: object. The commands are available from the ``flask`` command\n #: once the application has been discovered and blueprints have\n #: been registered.\n self.cli = AppGroup()\n\n #: A dictionary mapping endpoint names to view functions.\n #:\n #: To register a view function, use the :meth:`route` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.view_functions: t.Dict[str, t.Callable] = {}\n\n #: A data structure of registered error handlers, in the format\n #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n #: the name of a blueprint the handlers are active for, or\n #: ``None`` for all requests. The ``code`` key is the HTTP\n #: status code for ``HTTPException``, or ``None`` for\n #: other exceptions. The innermost dictionary maps exception\n #: classes to handler functions.\n #:\n #: To register an error handler, use the :meth:`errorhandler`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.error_handler_spec: t.Dict[\n ft.AppOrBlueprintKey,\n t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ft.ErrorHandlerCallable]],\n ] = defaultdict(lambda: defaultdict(dict))\n\n #: A data structure of functions to call at the beginning of\n #: each request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`before_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.before_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.BeforeRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`after_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.after_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.AfterRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request even if an exception is raised, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`teardown_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.teardown_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.TeardownCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call to pass extra context\n #: values when rendering templates, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`context_processor`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.template_context_processors: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.TemplateContextProcessorCallable]\n ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n #: A data structure of functions to call to modify the keyword\n #: arguments passed to the view function, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the\n #: :meth:`url_value_preprocessor` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_value_preprocessors: t.Dict[\n ft.AppOrBlueprintKey,\n t.List[ft.URLValuePreprocessorCallable],\n ] = defaultdict(list)\n\n #: A data structure of functions to call to modify the keyword\n #: arguments when generating URLs, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`url_defaults`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_default_functions: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.URLDefaultCallable]\n ] = defaultdict(list)"},{"attributeType":"Request","col":0,"comment":"null","endLoc":65,"id":123,"name":"request","nodeType":"Attribute","startLoc":65,"text":"request"},{"id":124,"name":"tests/test_apps/blueprintapp","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/blueprintapp","id":125,"nodeType":"File","text":"from flask import Flask\n\napp = Flask(__name__)\napp.config[\"DEBUG\"] = True\nfrom blueprintapp.apps.admin import admin # noqa: E402\nfrom blueprintapp.apps.frontend import frontend # noqa: E402\n\napp.register_blueprint(admin)\napp.register_blueprint(frontend)\n"},{"id":126,"name":"tests","nodeType":"Package"},{"fileName":"test_signals.py","filePath":"tests","id":127,"nodeType":"File","text":"import flask\n\n\ndef test_template_rendered(app, client):\n @app.route(\"/\")\n def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)\n\n recorded = []\n\n def record(sender, template, context):\n recorded.append((template, context))\n\n flask.template_rendered.connect(record, app)\n try:\n client.get(\"/\")\n assert len(recorded) == 1\n template, context = recorded[0]\n assert template.name == \"simple_template.html\"\n assert context[\"whiskey\"] == 42\n finally:\n flask.template_rendered.disconnect(record, app)\n\n\ndef test_before_render_template():\n app = flask.Flask(__name__)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)\n\n recorded = []\n\n def record(sender, template, context):\n context[\"whiskey\"] = 43\n recorded.append((template, context))\n\n flask.before_render_template.connect(record, app)\n try:\n rv = app.test_client().get(\"/\")\n assert len(recorded) == 1\n template, context = recorded[0]\n assert template.name == \"simple_template.html\"\n assert context[\"whiskey\"] == 43\n assert rv.data == b\"

43

\"\n finally:\n flask.before_render_template.disconnect(record, app)\n\n\ndef test_request_signals():\n app = flask.Flask(__name__)\n calls = []\n\n def before_request_signal(sender):\n calls.append(\"before-signal\")\n\n def after_request_signal(sender, response):\n assert response.data == b\"stuff\"\n calls.append(\"after-signal\")\n\n @app.before_request\n def before_request_handler():\n calls.append(\"before-handler\")\n\n @app.after_request\n def after_request_handler(response):\n calls.append(\"after-handler\")\n response.data = \"stuff\"\n return response\n\n @app.route(\"/\")\n def index():\n calls.append(\"handler\")\n return \"ignored anyway\"\n\n flask.request_started.connect(before_request_signal, app)\n flask.request_finished.connect(after_request_signal, app)\n\n try:\n rv = app.test_client().get(\"/\")\n assert rv.data == b\"stuff\"\n\n assert calls == [\n \"before-signal\",\n \"before-handler\",\n \"handler\",\n \"after-handler\",\n \"after-signal\",\n ]\n finally:\n flask.request_started.disconnect(before_request_signal, app)\n flask.request_finished.disconnect(after_request_signal, app)\n\n\ndef test_request_exception_signal():\n app = flask.Flask(__name__)\n recorded = []\n\n @app.route(\"/\")\n def index():\n 1 // 0\n\n def record(sender, exception):\n recorded.append(exception)\n\n flask.got_request_exception.connect(record, app)\n try:\n assert app.test_client().get(\"/\").status_code == 500\n assert len(recorded) == 1\n assert isinstance(recorded[0], ZeroDivisionError)\n finally:\n flask.got_request_exception.disconnect(record, app)\n\n\ndef test_appcontext_signals(app, client):\n recorded = []\n\n def record_push(sender, **kwargs):\n recorded.append(\"push\")\n\n def record_pop(sender, **kwargs):\n recorded.append(\"pop\")\n\n @app.route(\"/\")\n def index():\n return \"Hello\"\n\n flask.appcontext_pushed.connect(record_push, app)\n flask.appcontext_popped.connect(record_pop, app)\n try:\n rv = client.get(\"/\")\n assert rv.data == b\"Hello\"\n assert recorded == [\"push\", \"pop\"]\n finally:\n flask.appcontext_pushed.disconnect(record_push, app)\n flask.appcontext_popped.disconnect(record_pop, app)\n\n\ndef test_flash_signal(app):\n @app.route(\"/\")\n def index():\n flask.flash(\"This is a flash message\", category=\"notice\")\n return flask.redirect(\"/other\")\n\n recorded = []\n\n def record(sender, message, category):\n recorded.append((message, category))\n\n flask.message_flashed.connect(record, app)\n try:\n client = app.test_client()\n with client.session_transaction():\n client.get(\"/\")\n assert len(recorded) == 1\n message, category = recorded[0]\n assert message == \"This is a flash message\"\n assert category == \"notice\"\n finally:\n flask.message_flashed.disconnect(record, app)\n\n\ndef test_appcontext_tearing_down_signal(app, client):\n app.testing = False\n recorded = []\n\n def record_teardown(sender, exc):\n recorded.append(exc)\n\n @app.route(\"/\")\n def index():\n 1 // 0\n\n flask.appcontext_tearing_down.connect(record_teardown, app)\n try:\n rv = client.get(\"/\")\n assert rv.status_code == 500\n assert len(recorded) == 1\n assert isinstance(recorded[0], ZeroDivisionError)\n finally:\n flask.appcontext_tearing_down.disconnect(record_teardown, app)\n"},{"col":0,"comment":"null","endLoc":22,"header":"def test_template_rendered(app, client)","id":128,"name":"test_template_rendered","nodeType":"Function","startLoc":4,"text":"def test_template_rendered(app, client):\n @app.route(\"/\")\n def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)\n\n recorded = []\n\n def record(sender, template, context):\n recorded.append((template, context))\n\n flask.template_rendered.connect(record, app)\n try:\n client.get(\"/\")\n assert len(recorded) == 1\n template, context = recorded[0]\n assert template.name == \"simple_template.html\"\n assert context[\"whiskey\"] == 42\n finally:\n flask.template_rendered.disconnect(record, app)"},{"col":0,"comment":"Connect to the application's configured database. The connection\n is unique for each request and will be reused if this is called\n again.\n ","endLoc":19,"header":"def get_db()","id":129,"name":"get_db","nodeType":"Function","startLoc":8,"text":"def get_db():\n \"\"\"Connect to the application's configured database. The connection\n is unique for each request and will be reused if this is called\n again.\n \"\"\"\n if \"db\" not in g:\n g.db = sqlite3.connect(\n current_app.config[\"DATABASE\"], detect_types=sqlite3.PARSE_DECLTYPES\n )\n g.db.row_factory = sqlite3.Row\n\n return g.db"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":130,"name":"","nodeType":"Function","startLoc":1,"text":"application = Flask(__name__)"},{"fileName":"wrappers.py","filePath":"src/flask","id":131,"nodeType":"File","text":"import typing as t\n\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.wrappers import Request as RequestBase\nfrom werkzeug.wrappers import Response as ResponseBase\n\nfrom . import json\nfrom .globals import current_app\nfrom .helpers import _split_blueprint_path\n\nif t.TYPE_CHECKING: # pragma: no cover\n from werkzeug.routing import Rule\n\n\nclass Request(RequestBase):\n \"\"\"The request object used by default in Flask. Remembers the\n matched endpoint and view arguments.\n\n It is what ends up as :class:`~flask.request`. If you want to replace\n the request object used you can subclass this and set\n :attr:`~flask.Flask.request_class` to your subclass.\n\n The request object is a :class:`~werkzeug.wrappers.Request` subclass and\n provides all of the attributes Werkzeug defines plus a few Flask\n specific ones.\n \"\"\"\n\n json_module: t.Any = json\n\n #: The internal URL rule that matched the request. This can be\n #: useful to inspect which methods are allowed for the URL from\n #: a before/after handler (``request.url_rule.methods``) etc.\n #: Though if the request's method was invalid for the URL rule,\n #: the valid list is available in ``routing_exception.valid_methods``\n #: instead (an attribute of the Werkzeug exception\n #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)\n #: because the request was never internally bound.\n #:\n #: .. versionadded:: 0.6\n url_rule: t.Optional[\"Rule\"] = None\n\n #: A dict of view arguments that matched the request. If an exception\n #: happened when matching, this will be ``None``.\n view_args: t.Optional[t.Dict[str, t.Any]] = None\n\n #: If matching the URL failed, this is the exception that will be\n #: raised / was raised as part of the request handling. This is\n #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or\n #: something similar.\n routing_exception: t.Optional[Exception] = None\n\n @property\n def max_content_length(self) -> t.Optional[int]: # type: ignore\n \"\"\"Read-only view of the ``MAX_CONTENT_LENGTH`` config key.\"\"\"\n if current_app:\n return current_app.config[\"MAX_CONTENT_LENGTH\"]\n else:\n return None\n\n @property\n def endpoint(self) -> t.Optional[str]:\n \"\"\"The endpoint that matched the request URL.\n\n This will be ``None`` if matching failed or has not been\n performed yet.\n\n This in combination with :attr:`view_args` can be used to\n reconstruct the same URL or a modified URL.\n \"\"\"\n if self.url_rule is not None:\n return self.url_rule.endpoint\n\n return None\n\n @property\n def blueprint(self) -> t.Optional[str]:\n \"\"\"The registered name of the current blueprint.\n\n This will be ``None`` if the endpoint is not part of a\n blueprint, or if URL matching failed or has not been performed\n yet.\n\n This does not necessarily match the name the blueprint was\n created with. It may have been nested, or registered with a\n different name.\n \"\"\"\n endpoint = self.endpoint\n\n if endpoint is not None and \".\" in endpoint:\n return endpoint.rpartition(\".\")[0]\n\n return None\n\n @property\n def blueprints(self) -> t.List[str]:\n \"\"\"The registered names of the current blueprint upwards through\n parent blueprints.\n\n This will be an empty list if there is no current blueprint, or\n if URL matching failed.\n\n .. versionadded:: 2.0.1\n \"\"\"\n name = self.blueprint\n\n if name is None:\n return []\n\n return _split_blueprint_path(name)\n\n def _load_form_data(self) -> None:\n super()._load_form_data()\n\n # In debug mode we're replacing the files multidict with an ad-hoc\n # subclass that raises a different error for key errors.\n if (\n current_app\n and current_app.debug\n and self.mimetype != \"multipart/form-data\"\n and not self.files\n ):\n from .debughelpers import attach_enctype_error_multidict\n\n attach_enctype_error_multidict(self)\n\n def on_json_loading_failed(self, e: t.Optional[ValueError]) -> t.Any:\n try:\n return super().on_json_loading_failed(e)\n except BadRequest as e:\n if current_app and current_app.debug:\n raise\n\n raise BadRequest() from e\n\n\nclass Response(ResponseBase):\n \"\"\"The response object that is used by default in Flask. Works like the\n response object from Werkzeug but is set to have an HTML mimetype by\n default. Quite often you don't have to create this object yourself because\n :meth:`~flask.Flask.make_response` will take care of that for you.\n\n If you want to replace the response object used you can subclass this and\n set :attr:`~flask.Flask.response_class` to your subclass.\n\n .. versionchanged:: 1.0\n JSON support is added to the response, like the request. This is useful\n when testing to get the test client response data as JSON.\n\n .. versionchanged:: 1.0\n\n Added :attr:`max_cookie_size`.\n \"\"\"\n\n default_mimetype: t.Optional[str] = \"text/html\"\n\n json_module = json\n\n autocorrect_location_header = False\n\n @property\n def max_cookie_size(self) -> int: # type: ignore\n \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n Werkzeug's docs.\n \"\"\"\n if current_app:\n return current_app.config[\"MAX_COOKIE_SIZE\"]\n\n # return Werkzeug's default when not in an app context\n return super().max_cookie_size\n"},{"id":132,"name":"debugging.rst","nodeType":"TextFile","path":"docs","text":"Debugging Application Errors\n============================\n\n\nIn Production\n-------------\n\n**Do not run the development server, or enable the built-in debugger, in\na production environment.** The debugger allows executing arbitrary\nPython code from the browser. It's protected by a pin, but that should\nnot be relied on for security.\n\nUse an error logging tool, such as Sentry, as described in\n:ref:`error-logging-tools`, or enable logging and notifications as\ndescribed in :doc:`/logging`.\n\nIf you have access to the server, you could add some code to start an\nexternal debugger if ``request.remote_addr`` matches your IP. Some IDE\ndebuggers also have a remote mode so breakpoints on the server can be\ninteracted with locally. Only enable a debugger temporarily.\n\n\nThe Built-In Debugger\n---------------------\n\nThe built-in Werkzeug development server provides a debugger which shows\nan interactive traceback in the browser when an unhandled error occurs\nduring a request. This debugger should only be used during development.\n\n.. image:: _static/debugger.png\n :align: center\n :class: screenshot\n :alt: screenshot of debugger in action\n\n.. warning::\n\n The debugger allows executing arbitrary Python code from the\n browser. It is protected by a pin, but still represents a major\n security risk. Do not run the development server or debugger in a\n production environment.\n\nThe debugger is enabled by default when the development server is run in debug mode.\n\n.. code-block:: text\n\n $ flask --app hello run --debug\n\nWhen running from Python code, passing ``debug=True`` enables debug mode, which is\nmostly equivalent.\n\n.. code-block:: python\n\n app.run(debug=True)\n\n:doc:`/server` and :doc:`/cli` have more information about running the debugger and\ndebug mode. More information about the debugger can be found in the `Werkzeug\ndocumentation `__.\n\n\nExternal Debuggers\n------------------\n\nExternal debuggers, such as those provided by IDEs, can offer a more\npowerful debugging experience than the built-in debugger. They can also\nbe used to step through code during a request before an error is raised,\nor if no error is raised. Some even have a remote mode so you can debug\ncode running on another machine.\n\nWhen using an external debugger, the app should still be in debug mode,\nbut it can be useful to disable the built-in debugger and reloader,\nwhich can interfere.\n\n.. code-block:: text\n\n $ flask --app hello run --debug --no-debugger --no-reload\n\nWhen running from Python:\n\n.. code-block:: python\n\n app.run(debug=True, use_debugger=False, use_reloader=False)\n\nDisabling these isn't required, an external debugger will continue to\nwork with the following caveats. If the built-in debugger is not\ndisabled, it will catch unhandled exceptions before the external\ndebugger can. If the reloader is not disabled, it could cause an\nunexpected reload if code changes during debugging.\n"},{"id":133,"name":"contributing.rst","nodeType":"TextFile","path":"docs","text":".. include:: ../CONTRIBUTING.rst\n"},{"col":0,"comment":"Find the root path of a package, or the path that contains a\n module. If it cannot be found, returns the current working\n directory.\n\n Not to be confused with the value returned by :func:`find_package`.\n\n :meta private:\n ","endLoc":611,"header":"def get_root_path(import_name: str) -> str","id":134,"name":"get_root_path","nodeType":"Function","startLoc":565,"text":"def get_root_path(import_name: str) -> str:\n \"\"\"Find the root path of a package, or the path that contains a\n module. If it cannot be found, returns the current working\n directory.\n\n Not to be confused with the value returned by :func:`find_package`.\n\n :meta private:\n \"\"\"\n # Module already imported and has a file attribute. Use that first.\n mod = sys.modules.get(import_name)\n\n if mod is not None and hasattr(mod, \"__file__\") and mod.__file__ is not None:\n return os.path.dirname(os.path.abspath(mod.__file__))\n\n # Next attempt: check the loader.\n loader = pkgutil.get_loader(import_name)\n\n # Loader does not exist or we're referring to an unloaded main\n # module or a main module without path (interactive sessions), go\n # with the current working directory.\n if loader is None or import_name == \"__main__\":\n return os.getcwd()\n\n if hasattr(loader, \"get_filename\"):\n filepath = loader.get_filename(import_name)\n else:\n # Fall back to imports.\n __import__(import_name)\n mod = sys.modules[import_name]\n filepath = getattr(mod, \"__file__\", None)\n\n # If we don't have a file path it might be because it is a\n # namespace package. In this case pick the root path from the\n # first module that is contained in the package.\n if filepath is None:\n raise RuntimeError(\n \"No root path can be found for the provided module\"\n f\" {import_name!r}. This can happen because the module\"\n \" came from an import hook that does not provide file\"\n \" name information or because it's a namespace package.\"\n \" In this case the root path needs to be explicitly\"\n \" provided.\"\n )\n\n # filepath is import_name.py for a module, or __init__.py for a package.\n return os.path.dirname(os.path.abspath(filepath))"},{"fileName":"scaffold.py","filePath":"src/flask","id":135,"nodeType":"File","text":"import importlib.util\nimport os\nimport pathlib\nimport pkgutil\nimport sys\nimport typing as t\nfrom collections import defaultdict\nfrom datetime import timedelta\nfrom functools import update_wrapper\n\nfrom jinja2 import FileSystemLoader\nfrom werkzeug.exceptions import default_exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.utils import cached_property\n\nfrom . import typing as ft\nfrom .cli import AppGroup\nfrom .globals import current_app\nfrom .helpers import get_root_path\nfrom .helpers import send_from_directory\nfrom .templating import _default_template_ctx_processor\n\nif t.TYPE_CHECKING: # pragma: no cover\n from .wrappers import Response\n\n# a singleton sentinel value for parameter defaults\n_sentinel = object()\n\nF = t.TypeVar(\"F\", bound=t.Callable[..., t.Any])\nT_after_request = t.TypeVar(\"T_after_request\", bound=ft.AfterRequestCallable)\nT_before_request = t.TypeVar(\"T_before_request\", bound=ft.BeforeRequestCallable)\nT_error_handler = t.TypeVar(\"T_error_handler\", bound=ft.ErrorHandlerCallable)\nT_teardown = t.TypeVar(\"T_teardown\", bound=ft.TeardownCallable)\nT_template_context_processor = t.TypeVar(\n \"T_template_context_processor\", bound=ft.TemplateContextProcessorCallable\n)\nT_url_defaults = t.TypeVar(\"T_url_defaults\", bound=ft.URLDefaultCallable)\nT_url_value_preprocessor = t.TypeVar(\n \"T_url_value_preprocessor\", bound=ft.URLValuePreprocessorCallable\n)\nT_route = t.TypeVar(\"T_route\", bound=ft.RouteCallable)\n\n\ndef setupmethod(f: F) -> F:\n f_name = f.__name__\n\n def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:\n self._check_setup_finished(f_name)\n return f(self, *args, **kwargs)\n\n return t.cast(F, update_wrapper(wrapper_func, f))\n\n\nclass Scaffold:\n \"\"\"Common behavior shared between :class:`~flask.Flask` and\n :class:`~flask.blueprints.Blueprint`.\n\n :param import_name: The import name of the module where this object\n is defined. Usually :attr:`__name__` should be used.\n :param static_folder: Path to a folder of static files to serve.\n If this is set, a static route will be added.\n :param static_url_path: URL prefix for the static route.\n :param template_folder: Path to a folder containing template files.\n for rendering. If this is set, a Jinja loader will be added.\n :param root_path: The path that static, template, and resource files\n are relative to. Typically not set, it is discovered based on\n the ``import_name``.\n\n .. versionadded:: 2.0\n \"\"\"\n\n name: str\n _static_folder: t.Optional[str] = None\n _static_url_path: t.Optional[str] = None\n\n def __init__(\n self,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n root_path: t.Optional[str] = None,\n ):\n #: The name of the package or module that this object belongs\n #: to. Do not change this once it is set by the constructor.\n self.import_name = import_name\n\n self.static_folder = static_folder # type: ignore\n self.static_url_path = static_url_path\n\n #: The path to the templates folder, relative to\n #: :attr:`root_path`, to add to the template loader. ``None`` if\n #: templates should not be added.\n self.template_folder = template_folder\n\n if root_path is None:\n root_path = get_root_path(self.import_name)\n\n #: Absolute path to the package on the filesystem. Used to look\n #: up resources contained in the package.\n self.root_path = root_path\n\n #: The Click command group for registering CLI commands for this\n #: object. The commands are available from the ``flask`` command\n #: once the application has been discovered and blueprints have\n #: been registered.\n self.cli = AppGroup()\n\n #: A dictionary mapping endpoint names to view functions.\n #:\n #: To register a view function, use the :meth:`route` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.view_functions: t.Dict[str, t.Callable] = {}\n\n #: A data structure of registered error handlers, in the format\n #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is\n #: the name of a blueprint the handlers are active for, or\n #: ``None`` for all requests. The ``code`` key is the HTTP\n #: status code for ``HTTPException``, or ``None`` for\n #: other exceptions. The innermost dictionary maps exception\n #: classes to handler functions.\n #:\n #: To register an error handler, use the :meth:`errorhandler`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.error_handler_spec: t.Dict[\n ft.AppOrBlueprintKey,\n t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ft.ErrorHandlerCallable]],\n ] = defaultdict(lambda: defaultdict(dict))\n\n #: A data structure of functions to call at the beginning of\n #: each request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`before_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.before_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.BeforeRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request, in the format ``{scope: [functions]}``. The\n #: ``scope`` key is the name of a blueprint the functions are\n #: active for, or ``None`` for all requests.\n #:\n #: To register a function, use the :meth:`after_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.after_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.AfterRequestCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call at the end of each\n #: request even if an exception is raised, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`teardown_request`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.teardown_request_funcs: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.TeardownCallable]\n ] = defaultdict(list)\n\n #: A data structure of functions to call to pass extra context\n #: values when rendering templates, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`context_processor`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.template_context_processors: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.TemplateContextProcessorCallable]\n ] = defaultdict(list, {None: [_default_template_ctx_processor]})\n\n #: A data structure of functions to call to modify the keyword\n #: arguments passed to the view function, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the\n #: :meth:`url_value_preprocessor` decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_value_preprocessors: t.Dict[\n ft.AppOrBlueprintKey,\n t.List[ft.URLValuePreprocessorCallable],\n ] = defaultdict(list)\n\n #: A data structure of functions to call to modify the keyword\n #: arguments when generating URLs, in the format\n #: ``{scope: [functions]}``. The ``scope`` key is the name of a\n #: blueprint the functions are active for, or ``None`` for all\n #: requests.\n #:\n #: To register a function, use the :meth:`url_defaults`\n #: decorator.\n #:\n #: This data structure is internal. It should not be modified\n #: directly and its format may change at any time.\n self.url_default_functions: t.Dict[\n ft.AppOrBlueprintKey, t.List[ft.URLDefaultCallable]\n ] = defaultdict(list)\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__} {self.name!r}>\"\n\n def _check_setup_finished(self, f_name: str) -> None:\n raise NotImplementedError\n\n @property\n def static_folder(self) -> t.Optional[str]:\n \"\"\"The absolute path to the configured static folder. ``None``\n if no static folder is set.\n \"\"\"\n if self._static_folder is not None:\n return os.path.join(self.root_path, self._static_folder)\n else:\n return None\n\n @static_folder.setter\n def static_folder(self, value: t.Optional[t.Union[str, os.PathLike]]) -> None:\n if value is not None:\n value = os.fspath(value).rstrip(r\"\\/\")\n\n self._static_folder = value\n\n @property\n def has_static_folder(self) -> bool:\n \"\"\"``True`` if :attr:`static_folder` is set.\n\n .. versionadded:: 0.5\n \"\"\"\n return self.static_folder is not None\n\n @property\n def static_url_path(self) -> t.Optional[str]:\n \"\"\"The URL prefix that the static route will be accessible from.\n\n If it was not configured during init, it is derived from\n :attr:`static_folder`.\n \"\"\"\n if self._static_url_path is not None:\n return self._static_url_path\n\n if self.static_folder is not None:\n basename = os.path.basename(self.static_folder)\n return f\"/{basename}\".rstrip(\"/\")\n\n return None\n\n @static_url_path.setter\n def static_url_path(self, value: t.Optional[str]) -> None:\n if value is not None:\n value = value.rstrip(\"/\")\n\n self._static_url_path = value\n\n def get_send_file_max_age(self, filename: t.Optional[str]) -> t.Optional[int]:\n \"\"\"Used by :func:`send_file` to determine the ``max_age`` cache\n value for a given file path if it wasn't passed.\n\n By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from\n the configuration of :data:`~flask.current_app`. This defaults\n to ``None``, which tells the browser to use conditional requests\n instead of a timed cache, which is usually preferable.\n\n .. versionchanged:: 2.0\n The default configuration is ``None`` instead of 12 hours.\n\n .. versionadded:: 0.9\n \"\"\"\n value = current_app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"]\n\n if value is None:\n return None\n\n if isinstance(value, timedelta):\n return int(value.total_seconds())\n\n return value\n\n def send_static_file(self, filename: str) -> \"Response\":\n \"\"\"The view function used to serve files from\n :attr:`static_folder`. A route is automatically registered for\n this view at :attr:`static_url_path` if :attr:`static_folder` is\n set.\n\n .. versionadded:: 0.5\n \"\"\"\n if not self.has_static_folder:\n raise RuntimeError(\"'static_folder' must be set to serve static_files.\")\n\n # send_file only knows to call get_send_file_max_age on the app,\n # call it here so it works for blueprints too.\n max_age = self.get_send_file_max_age(filename)\n return send_from_directory(\n t.cast(str, self.static_folder), filename, max_age=max_age\n )\n\n @cached_property\n def jinja_loader(self) -> t.Optional[FileSystemLoader]:\n \"\"\"The Jinja loader for this object's templates. By default this\n is a class :class:`jinja2.loaders.FileSystemLoader` to\n :attr:`template_folder` if it is set.\n\n .. versionadded:: 0.5\n \"\"\"\n if self.template_folder is not None:\n return FileSystemLoader(os.path.join(self.root_path, self.template_folder))\n else:\n return None\n\n def open_resource(self, resource: str, mode: str = \"rb\") -> t.IO[t.AnyStr]:\n \"\"\"Open a resource file relative to :attr:`root_path` for\n reading.\n\n For example, if the file ``schema.sql`` is next to the file\n ``app.py`` where the ``Flask`` app is defined, it can be opened\n with:\n\n .. code-block:: python\n\n with app.open_resource(\"schema.sql\") as f:\n conn.executescript(f.read())\n\n :param resource: Path to the resource relative to\n :attr:`root_path`.\n :param mode: Open the file in this mode. Only reading is\n supported, valid values are \"r\" (or \"rt\") and \"rb\".\n \"\"\"\n if mode not in {\"r\", \"rt\", \"rb\"}:\n raise ValueError(\"Resources can only be opened for reading.\")\n\n return open(os.path.join(self.root_path, resource), mode)\n\n def _method_route(\n self,\n method: str,\n rule: str,\n options: dict,\n ) -> t.Callable[[T_route], T_route]:\n if \"methods\" in options:\n raise TypeError(\"Use the 'route' decorator to use the 'methods' argument.\")\n\n return self.route(rule, methods=[method], **options)\n\n @setupmethod\n def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"GET\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"GET\", rule, options)\n\n @setupmethod\n def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"POST\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"POST\", rule, options)\n\n @setupmethod\n def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PUT\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PUT\", rule, options)\n\n @setupmethod\n def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"DELETE\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"DELETE\", rule, options)\n\n @setupmethod\n def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Shortcut for :meth:`route` with ``methods=[\"PATCH\"]``.\n\n .. versionadded:: 2.0\n \"\"\"\n return self._method_route(\"PATCH\", rule, options)\n\n @setupmethod\n def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]:\n \"\"\"Decorate a view function to register it with the given URL\n rule and options. Calls :meth:`add_url_rule`, which has more\n details about the implementation.\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n return \"Hello, World!\"\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` and\n ``OPTIONS`` are added automatically.\n\n :param rule: The URL rule string.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n\n def decorator(f: T_route) -> T_route:\n endpoint = options.pop(\"endpoint\", None)\n self.add_url_rule(rule, endpoint, f, **options)\n return f\n\n return decorator\n\n @setupmethod\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[ft.RouteCallable] = None,\n provide_automatic_options: t.Optional[bool] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Register a rule for routing incoming requests and building\n URLs. The :meth:`route` decorator is a shortcut to call this\n with the ``view_func`` argument. These are equivalent:\n\n .. code-block:: python\n\n @app.route(\"/\")\n def index():\n ...\n\n .. code-block:: python\n\n def index():\n ...\n\n app.add_url_rule(\"/\", view_func=index)\n\n See :ref:`url-route-registrations`.\n\n The endpoint name for the route defaults to the name of the view\n function if the ``endpoint`` parameter isn't passed. An error\n will be raised if a function has already been registered for the\n endpoint.\n\n The ``methods`` parameter defaults to ``[\"GET\"]``. ``HEAD`` is\n always added automatically, and ``OPTIONS`` is added\n automatically by default.\n\n ``view_func`` does not necessarily need to be passed, but if the\n rule should participate in routing an endpoint name must be\n associated with a view function at some point with the\n :meth:`endpoint` decorator.\n\n .. code-block:: python\n\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n @app.endpoint(\"index\")\n def index():\n ...\n\n If ``view_func`` has a ``required_methods`` attribute, those\n methods are added to the passed and automatic methods. If it\n has a ``provide_automatic_methods`` attribute, it is used as the\n default if the parameter is not passed.\n\n :param rule: The URL rule string.\n :param endpoint: The endpoint name to associate with the rule\n and view function. Used when routing and building URLs.\n Defaults to ``view_func.__name__``.\n :param view_func: The view function to associate with the\n endpoint name.\n :param provide_automatic_options: Add the ``OPTIONS`` method and\n respond to ``OPTIONS`` requests automatically.\n :param options: Extra options passed to the\n :class:`~werkzeug.routing.Rule` object.\n \"\"\"\n raise NotImplementedError\n\n @setupmethod\n def endpoint(self, endpoint: str) -> t.Callable[[F], F]:\n \"\"\"Decorate a view function to register it for the given\n endpoint. Used if a rule is added without a ``view_func`` with\n :meth:`add_url_rule`.\n\n .. code-block:: python\n\n app.add_url_rule(\"/ex\", endpoint=\"example\")\n\n @app.endpoint(\"example\")\n def example():\n ...\n\n :param endpoint: The endpoint name to associate with the view\n function.\n \"\"\"\n\n def decorator(f: F) -> F:\n self.view_functions[endpoint] = f\n return f\n\n return decorator\n\n @setupmethod\n def before_request(self, f: T_before_request) -> T_before_request:\n \"\"\"Register a function to run before each request.\n\n For example, this can be used to open a database connection, or\n to load the logged in user from the session.\n\n .. code-block:: python\n\n @app.before_request\n def load_user():\n if \"user_id\" in session:\n g.user = db.session.get(session[\"user_id\"])\n\n The function will be called without any arguments. If it returns\n a non-``None`` value, the value is handled as if it was the\n return value from the view, and further request handling is\n stopped.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes before every request. When used on a blueprint, this executes before\n every request that the blueprint handles. To register with a blueprint and\n execute before every request, use :meth:`.Blueprint.before_app_request`.\n \"\"\"\n self.before_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def after_request(self, f: T_after_request) -> T_after_request:\n \"\"\"Register a function to run after each request to this object.\n\n The function is called with the response object, and must return\n a response object. This allows the functions to modify or\n replace the response before it is sent.\n\n If a function raises an exception, any remaining\n ``after_request`` functions will not be called. Therefore, this\n should not be used for actions that must execute, such as to\n close resources. Use :meth:`teardown_request` for that.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes after every request. When used on a blueprint, this executes after\n every request that the blueprint handles. To register with a blueprint and\n execute after every request, use :meth:`.Blueprint.after_app_request`.\n \"\"\"\n self.after_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def teardown_request(self, f: T_teardown) -> T_teardown:\n \"\"\"Register a function to be called when the request context is\n popped. Typically this happens at the end of each request, but\n contexts may be pushed manually as well during testing.\n\n .. code-block:: python\n\n with app.test_request_context():\n ...\n\n When the ``with`` block exits (or ``ctx.pop()`` is called), the\n teardown functions are called just before the request context is\n made inactive.\n\n When a teardown function was called because of an unhandled\n exception it will be passed an error object. If an\n :meth:`errorhandler` is registered, it will handle the exception\n and the teardown will not receive it.\n\n Teardown functions must avoid raising exceptions. If they\n execute code that might fail they must surround that code with a\n ``try``/``except`` block and log any errors.\n\n The return values of teardown functions are ignored.\n\n This is available on both app and blueprint objects. When used on an app, this\n executes after every request. When used on a blueprint, this executes after\n every request that the blueprint handles. To register with a blueprint and\n execute after every request, use :meth:`.Blueprint.teardown_app_request`.\n \"\"\"\n self.teardown_request_funcs.setdefault(None, []).append(f)\n return f\n\n @setupmethod\n def context_processor(\n self,\n f: T_template_context_processor,\n ) -> T_template_context_processor:\n \"\"\"Registers a template context processor function. These functions run before\n rendering a template. The keys of the returned dict are added as variables\n available in the template.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every rendered template. When used on a blueprint, this is called\n for templates rendered from the blueprint's views. To register with a blueprint\n and affect every template, use :meth:`.Blueprint.app_context_processor`.\n \"\"\"\n self.template_context_processors[None].append(f)\n return f\n\n @setupmethod\n def url_value_preprocessor(\n self,\n f: T_url_value_preprocessor,\n ) -> T_url_value_preprocessor:\n \"\"\"Register a URL value preprocessor function for all view\n functions in the application. These functions will be called before the\n :meth:`before_request` functions.\n\n The function can modify the values captured from the matched url before\n they are passed to the view. For example, this can be used to pop a\n common language code value and place it in ``g`` rather than pass it to\n every view.\n\n The function is passed the endpoint name and values dict. The return\n value is ignored.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every request. When used on a blueprint, this is called for\n requests that the blueprint handles. To register with a blueprint and affect\n every request, use :meth:`.Blueprint.app_url_value_preprocessor`.\n \"\"\"\n self.url_value_preprocessors[None].append(f)\n return f\n\n @setupmethod\n def url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n \"\"\"Callback function for URL defaults for all view functions of the\n application. It's called with the endpoint and values and should\n update the values passed in place.\n\n This is available on both app and blueprint objects. When used on an app, this\n is called for every request. When used on a blueprint, this is called for\n requests that the blueprint handles. To register with a blueprint and affect\n every request, use :meth:`.Blueprint.app_url_defaults`.\n \"\"\"\n self.url_default_functions[None].append(f)\n return f\n\n @setupmethod\n def errorhandler(\n self, code_or_exception: t.Union[t.Type[Exception], int]\n ) -> t.Callable[[T_error_handler], T_error_handler]:\n \"\"\"Register a function to handle errors by code or exception class.\n\n A decorator that is used to register a function given an\n error code. Example::\n\n @app.errorhandler(404)\n def page_not_found(error):\n return 'This page does not exist', 404\n\n You can also register handlers for arbitrary exceptions::\n\n @app.errorhandler(DatabaseError)\n def special_exception_handler(error):\n return 'Database connection failed', 500\n\n This is available on both app and blueprint objects. When used on an app, this\n can handle errors from every request. When used on a blueprint, this can handle\n errors from requests that the blueprint handles. To register with a blueprint\n and affect every request, use :meth:`.Blueprint.app_errorhandler`.\n\n .. versionadded:: 0.7\n Use :meth:`register_error_handler` instead of modifying\n :attr:`error_handler_spec` directly, for application wide error\n handlers.\n\n .. versionadded:: 0.7\n One can now additionally also register custom exception types\n that do not necessarily have to be a subclass of the\n :class:`~werkzeug.exceptions.HTTPException` class.\n\n :param code_or_exception: the code as integer for the handler, or\n an arbitrary exception\n \"\"\"\n\n def decorator(f: T_error_handler) -> T_error_handler:\n self.register_error_handler(code_or_exception, f)\n return f\n\n return decorator\n\n @setupmethod\n def register_error_handler(\n self,\n code_or_exception: t.Union[t.Type[Exception], int],\n f: ft.ErrorHandlerCallable,\n ) -> None:\n \"\"\"Alternative error attach function to the :meth:`errorhandler`\n decorator that is more straightforward to use for non decorator\n usage.\n\n .. versionadded:: 0.7\n \"\"\"\n exc_class, code = self._get_exc_class_and_code(code_or_exception)\n self.error_handler_spec[None][code][exc_class] = f\n\n @staticmethod\n def _get_exc_class_and_code(\n exc_class_or_code: t.Union[t.Type[Exception], int]\n ) -> t.Tuple[t.Type[Exception], t.Optional[int]]:\n \"\"\"Get the exception class being handled. For HTTP status codes\n or ``HTTPException`` subclasses, return both the exception and\n status code.\n\n :param exc_class_or_code: Any exception class, or an HTTP status\n code as an integer.\n \"\"\"\n exc_class: t.Type[Exception]\n\n if isinstance(exc_class_or_code, int):\n try:\n exc_class = default_exceptions[exc_class_or_code]\n except KeyError:\n raise ValueError(\n f\"'{exc_class_or_code}' is not a recognized HTTP\"\n \" error code. Use a subclass of HTTPException with\"\n \" that code instead.\"\n ) from None\n else:\n exc_class = exc_class_or_code\n\n if isinstance(exc_class, Exception):\n raise TypeError(\n f\"{exc_class!r} is an instance, not a class. Handlers\"\n \" can only be registered for Exception classes or HTTP\"\n \" error codes.\"\n )\n\n if not issubclass(exc_class, Exception):\n raise ValueError(\n f\"'{exc_class.__name__}' is not a subclass of Exception.\"\n \" Handlers can only be registered for Exception classes\"\n \" or HTTP error codes.\"\n )\n\n if issubclass(exc_class, HTTPException):\n return exc_class, exc_class.code\n else:\n return exc_class, None\n\n\ndef _endpoint_from_view_func(view_func: t.Callable) -> str:\n \"\"\"Internal helper that returns the default endpoint for a given\n function. This always is the function name.\n \"\"\"\n assert view_func is not None, \"expected view func if endpoint is not provided.\"\n return view_func.__name__\n\n\ndef _matching_loader_thinks_module_is_package(loader, mod_name):\n \"\"\"Attempt to figure out if the given name is a package or a module.\n\n :param: loader: The loader that handled the name.\n :param mod_name: The name of the package or module.\n \"\"\"\n # Use loader.is_package if it's available.\n if hasattr(loader, \"is_package\"):\n return loader.is_package(mod_name)\n\n cls = type(loader)\n\n # NamespaceLoader doesn't implement is_package, but all names it\n # loads must be packages.\n if cls.__module__ == \"_frozen_importlib\" and cls.__name__ == \"NamespaceLoader\":\n return True\n\n # Otherwise we need to fail with an error that explains what went\n # wrong.\n raise AttributeError(\n f\"'{cls.__name__}.is_package()' must be implemented for PEP 302\"\n f\" import hooks.\"\n )\n\n\ndef _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:\n # Path.is_relative_to doesn't exist until Python 3.9\n try:\n path.relative_to(base)\n return True\n except ValueError:\n return False\n\n\ndef _find_package_path(import_name):\n \"\"\"Find the path that contains the package or module.\"\"\"\n root_mod_name, _, _ = import_name.partition(\".\")\n\n try:\n root_spec = importlib.util.find_spec(root_mod_name)\n\n if root_spec is None:\n raise ValueError(\"not found\")\n # ImportError: the machinery told us it does not exist\n # ValueError:\n # - the module name was invalid\n # - the module name is __main__\n # - *we* raised `ValueError` due to `root_spec` being `None`\n except (ImportError, ValueError):\n pass # handled below\n else:\n # namespace package\n if root_spec.origin in {\"namespace\", None}:\n package_spec = importlib.util.find_spec(import_name)\n if package_spec is not None and package_spec.submodule_search_locations:\n # Pick the path in the namespace that contains the submodule.\n package_path = pathlib.Path(\n os.path.commonpath(package_spec.submodule_search_locations)\n )\n search_locations = (\n location\n for location in root_spec.submodule_search_locations\n if _path_is_relative_to(package_path, location)\n )\n else:\n # Pick the first path.\n search_locations = iter(root_spec.submodule_search_locations)\n return os.path.dirname(next(search_locations))\n # a package (with __init__.py)\n elif root_spec.submodule_search_locations:\n return os.path.dirname(os.path.dirname(root_spec.origin))\n # just a normal module\n else:\n return os.path.dirname(root_spec.origin)\n\n # we were unable to find the `package_path` using PEP 451 loaders\n loader = pkgutil.get_loader(root_mod_name)\n\n if loader is None or root_mod_name == \"__main__\":\n # import name is not found, or interactive/main module\n return os.getcwd()\n\n if hasattr(loader, \"get_filename\"):\n filename = loader.get_filename(root_mod_name)\n elif hasattr(loader, \"archive\"):\n # zipimporter's loader.archive points to the .egg or .zip file.\n filename = loader.archive\n else:\n # At least one loader is missing both get_filename and archive:\n # Google App Engine's HardenedModulesHook, use __file__.\n filename = importlib.import_module(root_mod_name).__file__\n\n package_path = os.path.abspath(os.path.dirname(filename))\n\n # If the imported name is a package, filename is currently pointing\n # to the root of the package, need to get the current directory.\n if _matching_loader_thinks_module_is_package(loader, root_mod_name):\n package_path = os.path.dirname(package_path)\n\n return package_path\n\n\ndef find_package(import_name: str):\n \"\"\"Find the prefix that a package is installed under, and the path\n that it would be imported from.\n\n The prefix is the directory containing the standard directory\n hierarchy (lib, bin, etc.). If the package is not installed to the\n system (:attr:`sys.prefix`) or a virtualenv (``site-packages``),\n ``None`` is returned.\n\n The path is the entry in :attr:`sys.path` that contains the package\n for import. If the package is not installed, it's assumed that the\n package was imported from the current working directory.\n \"\"\"\n package_path = _find_package_path(import_name)\n py_prefix = os.path.abspath(sys.prefix)\n\n # installed to the system\n if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):\n return py_prefix, package_path\n\n site_parent, site_folder = os.path.split(package_path)\n\n # installed to a virtualenv\n if site_folder.lower() == \"site-packages\":\n parent, folder = os.path.split(site_parent)\n\n # Windows (prefix/lib/site-packages)\n if folder.lower() == \"lib\":\n return parent, package_path\n\n # Unix (prefix/lib/pythonX.Y/site-packages)\n if os.path.basename(parent).lower() == \"lib\":\n return os.path.dirname(parent), package_path\n\n # something else (prefix/site-packages)\n return site_parent, package_path\n\n # not installed\n return None, package_path\n"},{"col":0,"comment":"null","endLoc":26,"header":"@bp.post(\"/add\")\ndef add() -> dict[str, object]","id":136,"name":"add","nodeType":"Function","startLoc":21,"text":"@bp.post(\"/add\")\ndef add() -> dict[str, object]:\n a = request.form.get(\"a\", type=int)\n b = request.form.get(\"b\", type=int)\n result = tasks.add.delay(a, b)\n return {\"result_id\": result.id}"},{"className":"HTTPStatus","col":0,"comment":"null","endLoc":92,"id":137,"nodeType":"Class","startLoc":13,"text":"class HTTPStatus(IntEnum):\n @property\n def phrase(self) -> str: ...\n @property\n def description(self) -> str: ...\n CONTINUE: int\n SWITCHING_PROTOCOLS: int\n PROCESSING: int\n OK: int\n CREATED: int\n ACCEPTED: int\n NON_AUTHORITATIVE_INFORMATION: int\n NO_CONTENT: int\n RESET_CONTENT: int\n PARTIAL_CONTENT: int\n MULTI_STATUS: int\n ALREADY_REPORTED: int\n IM_USED: int\n MULTIPLE_CHOICES: int\n MOVED_PERMANENTLY: int\n FOUND: int\n SEE_OTHER: int\n NOT_MODIFIED: int\n USE_PROXY: int\n TEMPORARY_REDIRECT: int\n PERMANENT_REDIRECT: int\n BAD_REQUEST: int\n UNAUTHORIZED: int\n PAYMENT_REQUIRED: int\n FORBIDDEN: int\n NOT_FOUND: int\n METHOD_NOT_ALLOWED: int\n NOT_ACCEPTABLE: int\n PROXY_AUTHENTICATION_REQUIRED: int\n REQUEST_TIMEOUT: int\n CONFLICT: int\n GONE: int\n LENGTH_REQUIRED: int\n PRECONDITION_FAILED: int\n REQUEST_ENTITY_TOO_LARGE: int\n REQUEST_URI_TOO_LONG: int\n UNSUPPORTED_MEDIA_TYPE: int\n REQUESTED_RANGE_NOT_SATISFIABLE: int\n EXPECTATION_FAILED: int\n UNPROCESSABLE_ENTITY: int\n LOCKED: int\n FAILED_DEPENDENCY: int\n UPGRADE_REQUIRED: int\n PRECONDITION_REQUIRED: int\n TOO_MANY_REQUESTS: int\n REQUEST_HEADER_FIELDS_TOO_LARGE: int\n INTERNAL_SERVER_ERROR: int\n NOT_IMPLEMENTED: int\n BAD_GATEWAY: int\n SERVICE_UNAVAILABLE: int\n GATEWAY_TIMEOUT: int\n HTTP_VERSION_NOT_SUPPORTED: int\n VARIANT_ALSO_NEGOTIATES: int\n INSUFFICIENT_STORAGE: int\n LOOP_DETECTED: int\n NOT_EXTENDED: int\n NETWORK_AUTHENTICATION_REQUIRED: int\n MISDIRECTED_REQUEST: int\n if sys.version_info >= (3, 8):\n UNAVAILABLE_FOR_LEGAL_REASONS: int\n if sys.version_info >= (3, 9):\n EARLY_HINTS: Literal[103]\n IM_A_TEAPOT: Literal[418]\n TOO_EARLY: Literal[425]\n if sys.version_info >= (3, 12):\n @property\n def is_informational(self) -> bool: ...\n @property\n def is_success(self) -> bool: ...\n @property\n def is_redirection(self) -> bool: ...\n @property\n def is_client_error(self) -> bool: ...\n @property\n def is_server_error(self) -> bool: ..."},{"col":0,"comment":"null","endLoc":13,"header":"@app.after_request\ndef after_sync(response: Response) -> Response","id":138,"name":"after_sync","nodeType":"Function","startLoc":11,"text":"@app.after_request\ndef after_sync(response: Response) -> Response:\n return Response()"},{"fileName":"test_regression.py","filePath":"tests","id":139,"nodeType":"File","text":"import flask\n\n\ndef test_aborting(app):\n class Foo(Exception):\n whatever = 42\n\n @app.errorhandler(Foo)\n def handle_foo(e):\n return str(e.whatever)\n\n @app.route(\"/\")\n def index():\n raise flask.abort(flask.redirect(flask.url_for(\"test\")))\n\n @app.route(\"/test\")\n def test():\n raise Foo()\n\n with app.test_client() as c:\n rv = c.get(\"/\")\n location_parts = rv.headers[\"Location\"].rpartition(\"/\")\n\n if location_parts[0]:\n # For older Werkzeug that used absolute redirects.\n assert location_parts[0] == \"http://localhost\"\n\n assert location_parts[2] == \"test\"\n rv = c.get(\"/test\")\n assert rv.data == b\"42\"\n"},{"col":0,"comment":"null","endLoc":18,"header":"@app.after_request\nasync def after_async(response: Response) -> Response","id":140,"name":"after_async","nodeType":"Function","startLoc":16,"text":"@app.after_request\nasync def after_async(response: Response) -> Response:\n return Response()"},{"col":0,"comment":"null","endLoc":30,"header":"def test_aborting(app)","id":141,"name":"test_aborting","nodeType":"Function","startLoc":4,"text":"def test_aborting(app):\n class Foo(Exception):\n whatever = 42\n\n @app.errorhandler(Foo)\n def handle_foo(e):\n return str(e.whatever)\n\n @app.route(\"/\")\n def index():\n raise flask.abort(flask.redirect(flask.url_for(\"test\")))\n\n @app.route(\"/test\")\n def test():\n raise Foo()\n\n with app.test_client() as c:\n rv = c.get(\"/\")\n location_parts = rv.headers[\"Location\"].rpartition(\"/\")\n\n if location_parts[0]:\n # For older Werkzeug that used absolute redirects.\n assert location_parts[0] == \"http://localhost\"\n\n assert location_parts[2] == \"test\"\n rv = c.get(\"/test\")\n assert rv.data == b\"42\""},{"col":0,"comment":"null","endLoc":23,"header":"@app.before_request\ndef before_sync() -> None","id":142,"name":"before_sync","nodeType":"Function","startLoc":21,"text":"@app.before_request\ndef before_sync() -> None:\n ..."},{"col":0,"comment":"null","endLoc":28,"header":"@app.before_request\nasync def before_async() -> None","id":143,"name":"before_async","nodeType":"Function","startLoc":26,"text":"@app.before_request\nasync def before_async() -> None:\n ..."},{"col":0,"comment":"null","endLoc":33,"header":"@app.teardown_appcontext\ndef teardown_sync(exc: t.Optional[BaseException]) -> None","id":144,"name":"teardown_sync","nodeType":"Function","startLoc":31,"text":"@app.teardown_appcontext\ndef teardown_sync(exc: t.Optional[BaseException]) -> None:\n ..."},{"col":0,"comment":"null","endLoc":38,"header":"@app.teardown_appcontext\nasync def teardown_async(exc: t.Optional[BaseException]) -> None","id":145,"name":"teardown_async","nodeType":"Function","startLoc":36,"text":"@app.teardown_appcontext\nasync def teardown_async(exc: t.Optional[BaseException]) -> None:\n ..."},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":146,"name":"t","nodeType":"Attribute","startLoc":3,"text":"t"},{"className":"HTTPStatus","col":0,"comment":"null","endLoc":92,"id":147,"nodeType":"Class","startLoc":13,"text":"class HTTPStatus(IntEnum):\n @property\n def phrase(self) -> str: ...\n @property\n def description(self) -> str: ...\n CONTINUE: int\n SWITCHING_PROTOCOLS: int\n PROCESSING: int\n OK: int\n CREATED: int\n ACCEPTED: int\n NON_AUTHORITATIVE_INFORMATION: int\n NO_CONTENT: int\n RESET_CONTENT: int\n PARTIAL_CONTENT: int\n MULTI_STATUS: int\n ALREADY_REPORTED: int\n IM_USED: int\n MULTIPLE_CHOICES: int\n MOVED_PERMANENTLY: int\n FOUND: int\n SEE_OTHER: int\n NOT_MODIFIED: int\n USE_PROXY: int\n TEMPORARY_REDIRECT: int\n PERMANENT_REDIRECT: int\n BAD_REQUEST: int\n UNAUTHORIZED: int\n PAYMENT_REQUIRED: int\n FORBIDDEN: int\n NOT_FOUND: int\n METHOD_NOT_ALLOWED: int\n NOT_ACCEPTABLE: int\n PROXY_AUTHENTICATION_REQUIRED: int\n REQUEST_TIMEOUT: int\n CONFLICT: int\n GONE: int\n LENGTH_REQUIRED: int\n PRECONDITION_FAILED: int\n REQUEST_ENTITY_TOO_LARGE: int\n REQUEST_URI_TOO_LONG: int\n UNSUPPORTED_MEDIA_TYPE: int\n REQUESTED_RANGE_NOT_SATISFIABLE: int\n EXPECTATION_FAILED: int\n UNPROCESSABLE_ENTITY: int\n LOCKED: int\n FAILED_DEPENDENCY: int\n UPGRADE_REQUIRED: int\n PRECONDITION_REQUIRED: int\n TOO_MANY_REQUESTS: int\n REQUEST_HEADER_FIELDS_TOO_LARGE: int\n INTERNAL_SERVER_ERROR: int\n NOT_IMPLEMENTED: int\n BAD_GATEWAY: int\n SERVICE_UNAVAILABLE: int\n GATEWAY_TIMEOUT: int\n HTTP_VERSION_NOT_SUPPORTED: int\n VARIANT_ALSO_NEGOTIATES: int\n INSUFFICIENT_STORAGE: int\n LOOP_DETECTED: int\n NOT_EXTENDED: int\n NETWORK_AUTHENTICATION_REQUIRED: int\n MISDIRECTED_REQUEST: int\n if sys.version_info >= (3, 8):\n UNAVAILABLE_FOR_LEGAL_REASONS: int\n if sys.version_info >= (3, 9):\n EARLY_HINTS: Literal[103]\n IM_A_TEAPOT: Literal[418]\n TOO_EARLY: Literal[425]\n if sys.version_info >= (3, 12):\n @property\n def is_informational(self) -> bool: ...\n @property\n def is_success(self) -> bool: ...\n @property\n def is_redirection(self) -> bool: ...\n @property\n def is_client_error(self) -> bool: ...\n @property\n def is_server_error(self) -> bool: ..."},{"fileName":"make_celery.py","filePath":"examples/celery","id":148,"nodeType":"File","text":"from task_app import create_app\n\nflask_app = create_app()\ncelery_app = flask_app.extensions[\"celery\"]\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":149,"name":"flask_app","nodeType":"Attribute","startLoc":3,"text":"flask_app"},{"attributeType":"null","col":0,"comment":"null","endLoc":4,"id":150,"name":"celery_app","nodeType":"Attribute","startLoc":4,"text":"celery_app"},{"col":0,"comment":"","endLoc":1,"header":"make_celery.py#","id":151,"name":"","nodeType":"Function","startLoc":1,"text":"flask_app = create_app()\n\ncelery_app = flask_app.extensions[\"celery\"]"},{"fileName":"flask.py","filePath":"tests/test_apps/cliapp/inner1/inner2","id":152,"nodeType":"File","text":"from flask import Flask\n\napp = Flask(__name__)\n"},{"fileName":"test_subclassing.py","filePath":"tests","id":153,"nodeType":"File","text":"from io import StringIO\n\nimport flask\n\n\ndef test_suppressed_exception_logging():\n class SuppressedFlask(flask.Flask):\n def log_exception(self, exc_info):\n pass\n\n out = StringIO()\n app = SuppressedFlask(__name__)\n\n @app.route(\"/\")\n def index():\n raise Exception(\"test\")\n\n rv = app.test_client().get(\"/\", errors_stream=out)\n assert rv.status_code == 500\n assert b\"Internal Server Error\" in rv.data\n assert not out.getvalue()\n"},{"className":"AuthActions","col":0,"comment":"null","endLoc":57,"id":154,"nodeType":"Class","startLoc":47,"text":"class AuthActions:\n def __init__(self, client):\n self._client = client\n\n def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )\n\n def logout(self):\n return self._client.get(\"/auth/logout\")"},{"col":4,"comment":"null","endLoc":49,"header":"def __init__(self, client)","id":155,"name":"__init__","nodeType":"Function","startLoc":48,"text":"def __init__(self, client):\n self._client = client"},{"col":4,"comment":"null","endLoc":54,"header":"def login(self, username=\"test\", password=\"test\")","id":156,"name":"login","nodeType":"Function","startLoc":51,"text":"def login(self, username=\"test\", password=\"test\"):\n return self._client.post(\n \"/auth/login\", data={\"username\": username, \"password\": password}\n )"},{"col":0,"comment":"null","endLoc":20,"header":"@admin.route(\"/index2\")\ndef index2()","id":157,"name":"index2","nodeType":"Function","startLoc":18,"text":"@admin.route(\"/index2\")\ndef index2():\n return render_template(\"./admin/index.html\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":4,"id":158,"name":"admin","nodeType":"Attribute","startLoc":4,"text":"admin"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":159,"name":"","nodeType":"Function","startLoc":1,"text":"admin = Blueprint(\n \"admin\",\n __name__,\n url_prefix=\"/admin\",\n template_folder=\"templates\",\n static_folder=\"static\",\n)"},{"className":"View","col":0,"comment":"Subclass this class and override :meth:`dispatch_request` to\n create a generic class-based view. Call :meth:`as_view` to create a\n view function that creates an instance of the class with the given\n arguments and calls its ``dispatch_request`` method with any URL\n variables.\n\n See :doc:`views` for a detailed guide.\n\n .. code-block:: python\n\n class Hello(View):\n init_every_request = False\n\n def dispatch_request(self, name):\n return f\"Hello, {name}!\"\n\n app.add_url_rule(\n \"/hello/\", view_func=Hello.as_view(\"hello\")\n )\n\n Set :attr:`methods` on the class to change what methods the view\n accepts.\n\n Set :attr:`decorators` on the class to apply a list of decorators to\n the generated view function. Decorators applied to the class itself\n will not be applied to the generated view function!\n\n Set :attr:`init_every_request` to ``False`` for efficiency, unless\n you need to store request-global data on ``self``.\n ","endLoc":132,"id":160,"nodeType":"Class","startLoc":13,"text":"class View:\n \"\"\"Subclass this class and override :meth:`dispatch_request` to\n create a generic class-based view. Call :meth:`as_view` to create a\n view function that creates an instance of the class with the given\n arguments and calls its ``dispatch_request`` method with any URL\n variables.\n\n See :doc:`views` for a detailed guide.\n\n .. code-block:: python\n\n class Hello(View):\n init_every_request = False\n\n def dispatch_request(self, name):\n return f\"Hello, {name}!\"\n\n app.add_url_rule(\n \"/hello/\", view_func=Hello.as_view(\"hello\")\n )\n\n Set :attr:`methods` on the class to change what methods the view\n accepts.\n\n Set :attr:`decorators` on the class to apply a list of decorators to\n the generated view function. Decorators applied to the class itself\n will not be applied to the generated view function!\n\n Set :attr:`init_every_request` to ``False`` for efficiency, unless\n you need to store request-global data on ``self``.\n \"\"\"\n\n #: The methods this view is registered for. Uses the same default\n #: (``[\"GET\", \"HEAD\", \"OPTIONS\"]``) as ``route`` and\n #: ``add_url_rule`` by default.\n methods: t.ClassVar[t.Optional[t.Collection[str]]] = None\n\n #: Control whether the ``OPTIONS`` method is handled automatically.\n #: Uses the same default (``True``) as ``route`` and\n #: ``add_url_rule`` by default.\n provide_automatic_options: t.ClassVar[t.Optional[bool]] = None\n\n #: A list of decorators to apply, in order, to the generated view\n #: function. Remember that ``@decorator`` syntax is applied bottom\n #: to top, so the first decorator in the list would be the bottom\n #: decorator.\n #:\n #: .. versionadded:: 0.8\n decorators: t.ClassVar[t.List[t.Callable]] = []\n\n #: Create a new instance of this view class for every request by\n #: default. If a view subclass sets this to ``False``, the same\n #: instance is used for every request.\n #:\n #: A single instance is more efficient, especially if complex setup\n #: is done during init. However, storing data on ``self`` is no\n #: longer safe across requests, and :data:`~flask.g` should be used\n #: instead.\n #:\n #: .. versionadded:: 2.2\n init_every_request: t.ClassVar[bool] = True\n\n def dispatch_request(self) -> ft.ResponseReturnValue:\n \"\"\"The actual view function behavior. Subclasses must override\n this and return a valid response. Any variables from the URL\n rule are passed as keyword arguments.\n \"\"\"\n raise NotImplementedError()\n\n @classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> ft.RouteCallable:\n \"\"\"Convert the class into a view function that can be registered\n for a route.\n\n By default, the generated view will create a new instance of the\n view class for every request and call its\n :meth:`dispatch_request` method. If the view class sets\n :attr:`init_every_request` to ``False``, the same instance will\n be used for every request.\n\n Except for ``name``, all other arguments passed to this method\n are forwarded to the view class ``__init__`` method.\n\n .. versionchanged:: 2.2\n Added the ``init_every_request`` class attribute.\n \"\"\"\n if cls.init_every_request:\n\n def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n self = view.view_class( # type: ignore[attr-defined]\n *class_args, **class_kwargs\n )\n return current_app.ensure_sync(self.dispatch_request)(**kwargs)\n\n else:\n self = cls(*class_args, **class_kwargs)\n\n def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n return current_app.ensure_sync(self.dispatch_request)(**kwargs)\n\n if cls.decorators:\n view.__name__ = name\n view.__module__ = cls.__module__\n for decorator in cls.decorators:\n view = decorator(view)\n\n # We attach the view class to the view function for two reasons:\n # first of all it allows us to easily figure out what class-based\n # view this thing came from, secondly it's also used for instantiating\n # the view class so you can actually replace it with something else\n # for testing purposes and debugging.\n view.view_class = cls # type: ignore\n view.__name__ = name\n view.__doc__ = cls.__doc__\n view.__module__ = cls.__module__\n view.methods = cls.methods # type: ignore\n view.provide_automatic_options = cls.provide_automatic_options # type: ignore\n return view"},{"col":4,"comment":"The actual view function behavior. Subclasses must override\n this and return a valid response. Any variables from the URL\n rule are passed as keyword arguments.\n ","endLoc":80,"header":"def dispatch_request(self) -> ft.ResponseReturnValue","id":161,"name":"dispatch_request","nodeType":"Function","startLoc":75,"text":"def dispatch_request(self) -> ft.ResponseReturnValue:\n \"\"\"The actual view function behavior. Subclasses must override\n this and return a valid response. Any variables from the URL\n rule are passed as keyword arguments.\n \"\"\"\n raise NotImplementedError()"},{"fileName":"importerrorapp.py","filePath":"tests/test_apps/cliapp","id":162,"nodeType":"File","text":"from flask import Flask\n\nraise ImportError()\n\ntestapp = Flask(\"testapp\")\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":5,"id":163,"name":"testapp","nodeType":"Attribute","startLoc":5,"text":"testapp"},{"col":0,"comment":"null","endLoc":696,"header":"@lru_cache(maxsize=None)\ndef _split_blueprint_path(name","id":164,"name":"_split_blueprint_path","nodeType":"Function","startLoc":689,"text":"@lru_cache(maxsize=None)\ndef _split_blueprint_path(name: str) -> t.List[str]:\n out: t.List[str] = [name]\n\n if \".\" in name:\n out.extend(_split_blueprint_path(name.rpartition(\".\")[0]))\n\n return out"},{"fileName":"logging.py","filePath":"src/flask","id":165,"nodeType":"File","text":"import logging\nimport sys\nimport typing as t\n\nfrom werkzeug.local import LocalProxy\n\nfrom .globals import request\n\nif t.TYPE_CHECKING: # pragma: no cover\n from .app import Flask\n\n\n@LocalProxy\ndef wsgi_errors_stream() -> t.TextIO:\n \"\"\"Find the most appropriate error stream for the application. If a request\n is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.\n\n If you configure your own :class:`logging.StreamHandler`, you may want to\n use this for the stream. If you are using file or dict configuration and\n can't import this directly, you can refer to it as\n ``ext://flask.logging.wsgi_errors_stream``.\n \"\"\"\n return request.environ[\"wsgi.errors\"] if request else sys.stderr\n\n\ndef has_level_handler(logger: logging.Logger) -> bool:\n \"\"\"Check if there is a handler in the logging chain that will handle the\n given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.\n \"\"\"\n level = logger.getEffectiveLevel()\n current = logger\n\n while current:\n if any(handler.level <= level for handler in current.handlers):\n return True\n\n if not current.propagate:\n break\n\n current = current.parent # type: ignore\n\n return False\n\n\n#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format\n#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.\ndefault_handler = logging.StreamHandler(wsgi_errors_stream) # type: ignore\ndefault_handler.setFormatter(\n logging.Formatter(\"[%(asctime)s] %(levelname)s in %(module)s: %(message)s\")\n)\n\n\ndef create_logger(app: \"Flask\") -> logging.Logger:\n \"\"\"Get the Flask app's logger and configure it if needed.\n\n The logger name will be the same as\n :attr:`app.import_name `.\n\n When :attr:`~flask.Flask.debug` is enabled, set the logger level to\n :data:`logging.DEBUG` if it is not set.\n\n If there is no handler for the logger's effective level, add a\n :class:`~logging.StreamHandler` for\n :func:`~flask.logging.wsgi_errors_stream` with a basic format.\n \"\"\"\n logger = logging.getLogger(app.name)\n\n if app.debug and not logger.level:\n logger.setLevel(logging.DEBUG)\n\n if not has_level_handler(logger):\n logger.addHandler(default_handler)\n\n return logger\n"},{"col":0,"comment":"","endLoc":1,"header":"importerrorapp.py#","id":168,"name":"","nodeType":"Function","startLoc":1,"text":"raise ImportError()\n\ntestapp = Flask(\"testapp\")"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":169,"name":"app","nodeType":"Attribute","startLoc":3,"text":"app"},{"attributeType":"null","col":0,"comment":"null","endLoc":8,"id":171,"name":"app","nodeType":"Attribute","startLoc":8,"text":"app"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":172,"name":"app","nodeType":"Attribute","startLoc":3,"text":"app"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":173,"name":"","nodeType":"Function","startLoc":1,"text":"app = Flask(__name__)\n\napp.config[\"DEBUG\"] = True\n\napp.register_blueprint(admin)\n\napp.register_blueprint(frontend)"},{"col":0,"comment":"","endLoc":1,"header":"typing_app_decorators.py#","id":174,"name":"","nodeType":"Function","startLoc":1,"text":"app = Flask(__name__)"},{"className":"StringIO","col":0,"comment":"null","endLoc":189,"id":175,"nodeType":"Class","startLoc":183,"text":"class StringIO(TextIOWrapper):\n def __init__(self, initial_value: str | None = ..., newline: str | None = ...) -> None: ...\n # StringIO does not contain a \"name\" field. This workaround is necessary\n # to allow StringIO sub-classes to add this field, as it is defined\n # as a read-only property on IO[].\n name: Any\n def getvalue(self) -> str: ..."},{"fileName":"test_user_error_handler.py","filePath":"tests","id":176,"nodeType":"File","text":"import pytest\nfrom werkzeug.exceptions import Forbidden\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.exceptions import InternalServerError\nfrom werkzeug.exceptions import NotFound\n\nimport flask\n\n\ndef test_error_handler_no_match(app, client):\n class CustomException(Exception):\n pass\n\n @app.errorhandler(CustomException)\n def custom_exception_handler(e):\n assert isinstance(e, CustomException)\n return \"custom\"\n\n with pytest.raises(TypeError) as exc_info:\n app.register_error_handler(CustomException(), None)\n\n assert \"CustomException() is an instance, not a class.\" in str(exc_info.value)\n\n with pytest.raises(ValueError) as exc_info:\n app.register_error_handler(list, None)\n\n assert \"'list' is not a subclass of Exception.\" in str(exc_info.value)\n\n @app.errorhandler(500)\n def handle_500(e):\n assert isinstance(e, InternalServerError)\n\n if e.original_exception is not None:\n return f\"wrapped {type(e.original_exception).__name__}\"\n\n return \"direct\"\n\n with pytest.raises(ValueError) as exc_info:\n app.register_error_handler(999, None)\n\n assert \"Use a subclass of HTTPException\" in str(exc_info.value)\n\n @app.route(\"/custom\")\n def custom_test():\n raise CustomException()\n\n @app.route(\"/keyerror\")\n def key_error():\n raise KeyError()\n\n @app.route(\"/abort\")\n def do_abort():\n flask.abort(500)\n\n app.testing = False\n assert client.get(\"/custom\").data == b\"custom\"\n assert client.get(\"/keyerror\").data == b\"wrapped KeyError\"\n assert client.get(\"/abort\").data == b\"direct\"\n\n\ndef test_error_handler_subclass(app):\n class ParentException(Exception):\n pass\n\n class ChildExceptionUnregistered(ParentException):\n pass\n\n class ChildExceptionRegistered(ParentException):\n pass\n\n @app.errorhandler(ParentException)\n def parent_exception_handler(e):\n assert isinstance(e, ParentException)\n return \"parent\"\n\n @app.errorhandler(ChildExceptionRegistered)\n def child_exception_handler(e):\n assert isinstance(e, ChildExceptionRegistered)\n return \"child-registered\"\n\n @app.route(\"/parent\")\n def parent_test():\n raise ParentException()\n\n @app.route(\"/child-unregistered\")\n def unregistered_test():\n raise ChildExceptionUnregistered()\n\n @app.route(\"/child-registered\")\n def registered_test():\n raise ChildExceptionRegistered()\n\n c = app.test_client()\n\n assert c.get(\"/parent\").data == b\"parent\"\n assert c.get(\"/child-unregistered\").data == b\"parent\"\n assert c.get(\"/child-registered\").data == b\"child-registered\"\n\n\ndef test_error_handler_http_subclass(app):\n class ForbiddenSubclassRegistered(Forbidden):\n pass\n\n class ForbiddenSubclassUnregistered(Forbidden):\n pass\n\n @app.errorhandler(403)\n def code_exception_handler(e):\n assert isinstance(e, Forbidden)\n return \"forbidden\"\n\n @app.errorhandler(ForbiddenSubclassRegistered)\n def subclass_exception_handler(e):\n assert isinstance(e, ForbiddenSubclassRegistered)\n return \"forbidden-registered\"\n\n @app.route(\"/forbidden\")\n def forbidden_test():\n raise Forbidden()\n\n @app.route(\"/forbidden-registered\")\n def registered_test():\n raise ForbiddenSubclassRegistered()\n\n @app.route(\"/forbidden-unregistered\")\n def unregistered_test():\n raise ForbiddenSubclassUnregistered()\n\n c = app.test_client()\n\n assert c.get(\"/forbidden\").data == b\"forbidden\"\n assert c.get(\"/forbidden-unregistered\").data == b\"forbidden\"\n assert c.get(\"/forbidden-registered\").data == b\"forbidden-registered\"\n\n\ndef test_error_handler_blueprint(app):\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.errorhandler(500)\n def bp_exception_handler(e):\n return \"bp-error\"\n\n @bp.route(\"/error\")\n def bp_test():\n raise InternalServerError()\n\n @app.errorhandler(500)\n def app_exception_handler(e):\n return \"app-error\"\n\n @app.route(\"/error\")\n def app_test():\n raise InternalServerError()\n\n app.register_blueprint(bp, url_prefix=\"/bp\")\n\n c = app.test_client()\n\n assert c.get(\"/error\").data == b\"app-error\"\n assert c.get(\"/bp/error\").data == b\"bp-error\"\n\n\ndef test_default_error_handler():\n bp = flask.Blueprint(\"bp\", __name__)\n\n @bp.errorhandler(HTTPException)\n def bp_exception_handler(e):\n assert isinstance(e, HTTPException)\n assert isinstance(e, NotFound)\n return \"bp-default\"\n\n @bp.errorhandler(Forbidden)\n def bp_forbidden_handler(e):\n assert isinstance(e, Forbidden)\n return \"bp-forbidden\"\n\n @bp.route(\"/undefined\")\n def bp_registered_test():\n raise NotFound()\n\n @bp.route(\"/forbidden\")\n def bp_forbidden_test():\n raise Forbidden()\n\n app = flask.Flask(__name__)\n\n @app.errorhandler(HTTPException)\n def catchall_exception_handler(e):\n assert isinstance(e, HTTPException)\n assert isinstance(e, NotFound)\n return \"default\"\n\n @app.errorhandler(Forbidden)\n def catchall_forbidden_handler(e):\n assert isinstance(e, Forbidden)\n return \"forbidden\"\n\n @app.route(\"/forbidden\")\n def forbidden():\n raise Forbidden()\n\n @app.route(\"/slash/\")\n def slash():\n return \"slash\"\n\n app.register_blueprint(bp, url_prefix=\"/bp\")\n\n c = app.test_client()\n assert c.get(\"/bp/undefined\").data == b\"bp-default\"\n assert c.get(\"/bp/forbidden\").data == b\"bp-forbidden\"\n assert c.get(\"/undefined\").data == b\"default\"\n assert c.get(\"/forbidden\").data == b\"forbidden\"\n # Don't handle RequestRedirect raised when adding slash.\n assert c.get(\"/slash\", follow_redirects=True).data == b\"slash\"\n\n\nclass TestGenericHandlers:\n \"\"\"Test how very generic handlers are dispatched to.\"\"\"\n\n class Custom(Exception):\n pass\n\n @pytest.fixture()\n def app(self, app):\n @app.route(\"/custom\")\n def do_custom():\n raise self.Custom()\n\n @app.route(\"/error\")\n def do_error():\n raise KeyError()\n\n @app.route(\"/abort\")\n def do_abort():\n flask.abort(500)\n\n @app.route(\"/raise\")\n def do_raise():\n raise InternalServerError()\n\n app.config[\"PROPAGATE_EXCEPTIONS\"] = False\n return app\n\n def report_error(self, e):\n original = getattr(e, \"original_exception\", None)\n\n if original is not None:\n return f\"wrapped {type(original).__name__}\"\n\n return f\"direct {type(e).__name__}\"\n\n @pytest.mark.parametrize(\"to_handle\", (InternalServerError, 500))\n def test_handle_class_or_code(self, app, client, to_handle):\n \"\"\"``InternalServerError`` and ``500`` are aliases, they should\n have the same behavior. Both should only receive\n ``InternalServerError``, which might wrap another error.\n \"\"\"\n\n @app.errorhandler(to_handle)\n def handle_500(e):\n assert isinstance(e, InternalServerError)\n return self.report_error(e)\n\n assert client.get(\"/custom\").data == b\"wrapped Custom\"\n assert client.get(\"/error\").data == b\"wrapped KeyError\"\n assert client.get(\"/abort\").data == b\"direct InternalServerError\"\n assert client.get(\"/raise\").data == b\"direct InternalServerError\"\n\n def test_handle_generic_http(self, app, client):\n \"\"\"``HTTPException`` should only receive ``HTTPException``\n subclasses. It will receive ``404`` routing exceptions.\n \"\"\"\n\n @app.errorhandler(HTTPException)\n def handle_http(e):\n assert isinstance(e, HTTPException)\n return str(e.code)\n\n assert client.get(\"/error\").data == b\"500\"\n assert client.get(\"/abort\").data == b\"500\"\n assert client.get(\"/not-found\").data == b\"404\"\n\n def test_handle_generic(self, app, client):\n \"\"\"Generic ``Exception`` will handle all exceptions directly,\n including ``HTTPExceptions``.\n \"\"\"\n\n @app.errorhandler(Exception)\n def handle_exception(e):\n return self.report_error(e)\n\n assert client.get(\"/custom\").data == b\"direct Custom\"\n assert client.get(\"/error\").data == b\"direct KeyError\"\n assert client.get(\"/abort\").data == b\"direct InternalServerError\"\n assert client.get(\"/not-found\").data == b\"direct NotFound\"\n"},{"className":"TestGenericHandlers","col":0,"comment":"Test how very generic handlers are dispatched to.","endLoc":295,"id":177,"nodeType":"Class","startLoc":217,"text":"class TestGenericHandlers:\n \"\"\"Test how very generic handlers are dispatched to.\"\"\"\n\n class Custom(Exception):\n pass\n\n @pytest.fixture()\n def app(self, app):\n @app.route(\"/custom\")\n def do_custom():\n raise self.Custom()\n\n @app.route(\"/error\")\n def do_error():\n raise KeyError()\n\n @app.route(\"/abort\")\n def do_abort():\n flask.abort(500)\n\n @app.route(\"/raise\")\n def do_raise():\n raise InternalServerError()\n\n app.config[\"PROPAGATE_EXCEPTIONS\"] = False\n return app\n\n def report_error(self, e):\n original = getattr(e, \"original_exception\", None)\n\n if original is not None:\n return f\"wrapped {type(original).__name__}\"\n\n return f\"direct {type(e).__name__}\"\n\n @pytest.mark.parametrize(\"to_handle\", (InternalServerError, 500))\n def test_handle_class_or_code(self, app, client, to_handle):\n \"\"\"``InternalServerError`` and ``500`` are aliases, they should\n have the same behavior. Both should only receive\n ``InternalServerError``, which might wrap another error.\n \"\"\"\n\n @app.errorhandler(to_handle)\n def handle_500(e):\n assert isinstance(e, InternalServerError)\n return self.report_error(e)\n\n assert client.get(\"/custom\").data == b\"wrapped Custom\"\n assert client.get(\"/error\").data == b\"wrapped KeyError\"\n assert client.get(\"/abort\").data == b\"direct InternalServerError\"\n assert client.get(\"/raise\").data == b\"direct InternalServerError\"\n\n def test_handle_generic_http(self, app, client):\n \"\"\"``HTTPException`` should only receive ``HTTPException``\n subclasses. It will receive ``404`` routing exceptions.\n \"\"\"\n\n @app.errorhandler(HTTPException)\n def handle_http(e):\n assert isinstance(e, HTTPException)\n return str(e.code)\n\n assert client.get(\"/error\").data == b\"500\"\n assert client.get(\"/abort\").data == b\"500\"\n assert client.get(\"/not-found\").data == b\"404\"\n\n def test_handle_generic(self, app, client):\n \"\"\"Generic ``Exception`` will handle all exceptions directly,\n including ``HTTPExceptions``.\n \"\"\"\n\n @app.errorhandler(Exception)\n def handle_exception(e):\n return self.report_error(e)\n\n assert client.get(\"/custom\").data == b\"direct Custom\"\n assert client.get(\"/error\").data == b\"direct KeyError\"\n assert client.get(\"/abort\").data == b\"direct InternalServerError\"\n assert client.get(\"/not-found\").data == b\"direct NotFound\""},{"id":178,"name":"escaping_template.html","nodeType":"TextFile","path":"tests/templates","text":"{{ text }}\n{{ html }}\n{% autoescape false %}{{ text }}\n{{ html }}{% endautoescape %}\n{% autoescape true %}{{ text }}\n{{ html }}{% endautoescape %}\n"},{"col":4,"comment":"null","endLoc":242,"header":"@pytest.fixture()\n def app(self, app)","id":179,"name":"app","nodeType":"Function","startLoc":223,"text":"@pytest.fixture()\n def app(self, app):\n @app.route(\"/custom\")\n def do_custom():\n raise self.Custom()\n\n @app.route(\"/error\")\n def do_error():\n raise KeyError()\n\n @app.route(\"/abort\")\n def do_abort():\n flask.abort(500)\n\n @app.route(\"/raise\")\n def do_raise():\n raise InternalServerError()\n\n app.config[\"PROPAGATE_EXCEPTIONS\"] = False\n return app"},{"fileName":"test_helpers.py","filePath":"tests","id":180,"nodeType":"File","text":"import io\nimport os\n\nimport pytest\nimport werkzeug.exceptions\n\nimport flask\nfrom flask.helpers import get_debug_flag\n\n\nclass FakePath:\n \"\"\"Fake object to represent a ``PathLike object``.\n\n This represents a ``pathlib.Path`` object in python 3.\n See: https://www.python.org/dev/peps/pep-0519/\n \"\"\"\n\n def __init__(self, path):\n self.path = path\n\n def __fspath__(self):\n return self.path\n\n\nclass PyBytesIO:\n def __init__(self, *args, **kwargs):\n self._io = io.BytesIO(*args, **kwargs)\n\n def __getattr__(self, name):\n return getattr(self._io, name)\n\n\nclass TestSendfile:\n def test_send_file(self, app, req_ctx):\n rv = flask.send_file(\"static/index.html\")\n assert rv.direct_passthrough\n assert rv.mimetype == \"text/html\"\n\n with app.open_resource(\"static/index.html\") as f:\n rv.direct_passthrough = False\n assert rv.data == f.read()\n\n rv.close()\n\n def test_static_file(self, app, req_ctx):\n # Default max_age is None.\n\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age is None\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age is None\n rv.close()\n\n app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = 3600\n\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n # Test with pathlib.Path.\n rv = app.send_static_file(FakePath(\"index.html\"))\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n class StaticFileApp(flask.Flask):\n def get_send_file_max_age(self, filename):\n return 10\n\n app = StaticFileApp(__name__)\n\n with app.test_request_context():\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age == 10\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age == 10\n rv.close()\n\n def test_send_from_directory(self, app, req_ctx):\n app.root_path = os.path.join(\n os.path.dirname(__file__), \"test_apps\", \"subdomaintestmodule\"\n )\n rv = flask.send_from_directory(\"static\", \"hello.txt\")\n rv.direct_passthrough = False\n assert rv.data.strip() == b\"Hello Subdomain\"\n rv.close()\n\n\nclass TestUrlFor:\n def test_url_for_with_anchor(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _anchor=\"x y\") == \"/#x%20y\"\n\n def test_url_for_with_scheme(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )\n\n def test_url_for_with_scheme_not_external(self, app, req_ctx):\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n # Implicit external with scheme.\n url = flask.url_for(\"index\", _scheme=\"https\")\n assert url == \"https://localhost/\"\n\n # Error when external=False with scheme\n with pytest.raises(ValueError):\n flask.url_for(\"index\", _scheme=\"https\", _external=False)\n\n def test_url_for_with_alternating_schemes(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\"\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\"\n\n def test_url_with_method(self, app, req_ctx):\n from flask.views import MethodView\n\n class MyView(MethodView):\n def get(self, id=None):\n if id is None:\n return \"List\"\n return f\"Get {id:d}\"\n\n def post(self):\n return \"Create\"\n\n myview = MyView.as_view(\"myview\")\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/create\", methods=[\"POST\"], view_func=myview)\n\n assert flask.url_for(\"myview\", _method=\"GET\") == \"/myview/\"\n assert flask.url_for(\"myview\", id=42, _method=\"GET\") == \"/myview/42\"\n assert flask.url_for(\"myview\", _method=\"POST\") == \"/myview/create\"\n\n\ndef test_redirect_no_app():\n response = flask.redirect(\"https://localhost\", 307)\n assert response.location == \"https://localhost\"\n assert response.status_code == 307\n\n\ndef test_redirect_with_app(app):\n def redirect(location, code=302):\n raise ValueError\n\n app.redirect = redirect\n\n with app.app_context(), pytest.raises(ValueError):\n flask.redirect(\"other\")\n\n\ndef test_abort_no_app():\n with pytest.raises(werkzeug.exceptions.Unauthorized):\n flask.abort(401)\n\n with pytest.raises(LookupError):\n flask.abort(900)\n\n\ndef test_app_aborter_class():\n class MyAborter(werkzeug.exceptions.Aborter):\n pass\n\n class MyFlask(flask.Flask):\n aborter_class = MyAborter\n\n app = MyFlask(__name__)\n assert isinstance(app.aborter, MyAborter)\n\n\ndef test_abort_with_app(app):\n class My900Error(werkzeug.exceptions.HTTPException):\n code = 900\n\n app.aborter.mapping[900] = My900Error\n\n with app.app_context(), pytest.raises(My900Error):\n flask.abort(900)\n\n\nclass TestNoImports:\n \"\"\"Test Flasks are created without import.\n\n Avoiding ``__import__`` helps create Flask instances where there are errors\n at import time. Those runtime errors will be apparent to the user soon\n enough, but tools which build Flask instances meta-programmatically benefit\n from a Flask which does not ``__import__``. Instead of importing to\n retrieve file paths or metadata on a module or package, use the pkgutil and\n imp modules in the Python standard library.\n \"\"\"\n\n def test_name_with_import_error(self, modules_tmpdir):\n modules_tmpdir.join(\"importerror.py\").write(\"raise NotImplementedError()\")\n try:\n flask.Flask(\"importerror\")\n except NotImplementedError:\n AssertionError(\"Flask(import_name) is importing import_name.\")\n\n\nclass TestStreaming:\n def test_streaming_with_context(self, app, client):\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(generate()))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n\n def test_streaming_with_context_as_decorator(self, app, client):\n @app.route(\"/\")\n def index():\n @flask.stream_with_context\n def generate(hello):\n yield hello\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(generate(\"Hello \"))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n\n def test_streaming_with_context_and_custom_close(self, app, client):\n called = []\n\n class Wrapper:\n def __init__(self, gen):\n self._gen = gen\n\n def __iter__(self):\n return self\n\n def close(self):\n called.append(42)\n\n def __next__(self):\n return next(self._gen)\n\n next = __next__\n\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(Wrapper(generate())))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n assert called == [42]\n\n def test_stream_keeps_session(self, app, client):\n @app.route(\"/\")\n def index():\n flask.session[\"test\"] = \"flask\"\n\n @flask.stream_with_context\n def gen():\n yield flask.session[\"test\"]\n\n return flask.Response(gen())\n\n rv = client.get(\"/\")\n assert rv.data == b\"flask\"\n\n\nclass TestHelpers:\n @pytest.mark.parametrize(\n (\"debug\", \"expect\"),\n [\n (\"\", False),\n (\"0\", False),\n (\"False\", False),\n (\"No\", False),\n (\"True\", True),\n ],\n )\n def test_get_debug_flag(self, monkeypatch, debug, expect):\n monkeypatch.setenv(\"FLASK_DEBUG\", debug)\n assert get_debug_flag() == expect\n\n def test_make_response(self):\n app = flask.Flask(__name__)\n with app.test_request_context():\n rv = flask.helpers.make_response()\n assert rv.status_code == 200\n assert rv.mimetype == \"text/html\"\n\n rv = flask.helpers.make_response(\"Hello\")\n assert rv.status_code == 200\n assert rv.data == b\"Hello\"\n assert rv.mimetype == \"text/html\"\n\n @pytest.mark.parametrize(\"mode\", (\"r\", \"rb\", \"rt\"))\n def test_open_resource(self, mode):\n app = flask.Flask(__name__)\n\n with app.open_resource(\"static/index.html\", mode) as f:\n assert \"

Hello World!

\" in str(f.read())\n\n @pytest.mark.parametrize(\"mode\", (\"w\", \"x\", \"a\", \"r+\"))\n def test_open_resource_exceptions(self, mode):\n app = flask.Flask(__name__)\n\n with pytest.raises(ValueError):\n app.open_resource(\"static/index.html\", mode)\n"},{"id":181,"name":"tests/test_apps/blueprintapp/apps/admin/templates/admin","nodeType":"Package"},{"id":182,"name":"index.html","nodeType":"TextFile","path":"tests/test_apps/blueprintapp/apps/admin/templates/admin","text":"Hello from the Admin\n"},{"id":183,"name":"README.rst","nodeType":"TextFile","path":"","text":"Flask\n=====\n\nFlask is a lightweight `WSGI`_ web application framework. It is designed\nto make getting started quick and easy, with the ability to scale up to\ncomplex applications. It began as a simple wrapper around `Werkzeug`_\nand `Jinja`_ and has become one of the most popular Python web\napplication frameworks.\n\nFlask offers suggestions, but doesn't enforce any dependencies or\nproject layout. It is up to the developer to choose the tools and\nlibraries they want to use. There are many extensions provided by the\ncommunity that make adding new functionality easy.\n\n.. _WSGI: https://wsgi.readthedocs.io/\n.. _Werkzeug: https://werkzeug.palletsprojects.com/\n.. _Jinja: https://jinja.palletsprojects.com/\n\n\nInstalling\n----------\n\nInstall and update using `pip`_:\n\n.. code-block:: text\n\n $ pip install -U Flask\n\n.. _pip: https://pip.pypa.io/en/stable/getting-started/\n\n\nA Simple Example\n----------------\n\n.. code-block:: python\n\n # save this as app.py\n from flask import Flask\n\n app = Flask(__name__)\n\n @app.route(\"/\")\n def hello():\n return \"Hello, World!\"\n\n.. code-block:: text\n\n $ flask run\n * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n\n\nContributing\n------------\n\nFor guidance on setting up a development environment and how to make a\ncontribution to Flask, see the `contributing guidelines`_.\n\n.. _contributing guidelines: https://github.com/pallets/flask/blob/main/CONTRIBUTING.rst\n\n\nDonate\n------\n\nThe Pallets organization develops and supports Flask and the libraries\nit uses. In order to grow the community of contributors and users, and\nallow the maintainers to devote more time to the projects, `please\ndonate today`_.\n\n.. _please donate today: https://palletsprojects.com/donate\n\n\nLinks\n-----\n\n- Documentation: https://flask.palletsprojects.com/\n- Changes: https://flask.palletsprojects.com/changes/\n- PyPI Releases: https://pypi.org/project/Flask/\n- Source Code: https://github.com/pallets/flask/\n- Issue Tracker: https://github.com/pallets/flask/issues/\n- Website: https://palletsprojects.com/p/flask/\n- Twitter: https://twitter.com/PalletsTeam\n- Chat: https://discord.gg/pallets\n"},{"id":185,"name":"schema.sql","nodeType":"TextFile","path":"examples/tutorial/flaskr","text":"-- Initialize the database.\n-- Drop any existing data and create empty tables.\n\nDROP TABLE IF EXISTS user;\nDROP TABLE IF EXISTS post;\n\nCREATE TABLE user (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n username TEXT UNIQUE NOT NULL,\n password TEXT NOT NULL\n);\n\nCREATE TABLE post (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n author_id INTEGER NOT NULL,\n created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n title TEXT NOT NULL,\n body TEXT NOT NULL,\n FOREIGN KEY (author_id) REFERENCES user (id)\n);\n"},{"id":189,"name":"eventlet.rst","nodeType":"TextFile","path":"docs/deploying","text":"eventlet\n========\n\nPrefer using :doc:`gunicorn` with eventlet workers rather than using\n`eventlet`_ directly. Gunicorn provides a much more configurable and\nproduction-tested server.\n\n`eventlet`_ allows writing asynchronous, coroutine-based code that looks\nlike standard synchronous Python. It uses `greenlet`_ to enable task\nswitching without writing ``async/await`` or using ``asyncio``.\n\n:doc:`gevent` is another library that does the same thing. Certain\ndependencies you have, or other considerations, may affect which of the\ntwo you choose to use.\n\neventlet provides a WSGI server that can handle many connections at once\ninstead of one per worker process. You must actually use eventlet in\nyour own code to see any benefit to using the server.\n\n.. _eventlet: https://eventlet.net/\n.. _greenlet: https://greenlet.readthedocs.io/en/latest/\n\n\nInstalling\n----------\n\nWhen using eventlet, greenlet>=1.0 is required, otherwise context locals\nsuch as ``request`` will not work as expected. When using PyPy,\nPyPy>=7.3.7 is required.\n\nCreate a virtualenv, install your application, then install\n``eventlet``.\n\n.. code-block:: text\n\n $ cd hello-app\n $ python -m venv .venv\n $ . .venv/bin/activate\n $ pip install . # install your application\n $ pip install eventlet\n\n\nRunning\n-------\n\nTo use eventlet to serve your application, write a script that imports\nits ``wsgi.server``, as well as your app or app factory.\n\n.. code-block:: python\n :caption: ``wsgi.py``\n\n import eventlet\n from eventlet import wsgi\n from hello import create_app\n\n app = create_app()\n wsgi.server(eventlet.listen((\"127.0.0.1\", 8000), app)\n\n.. code-block:: text\n\n $ python wsgi.py\n (x) wsgi starting up on http://127.0.0.1:8000\n\n\nBinding Externally\n------------------\n\neventlet should not be run as root because it would cause your\napplication code to run as root, which is not secure. However, this\nmeans it will not be possible to bind to port 80 or 443. Instead, a\nreverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used\nin front of eventlet.\n\nYou can bind to all external IPs on a non-privileged port by using\n``0.0.0.0`` in the server arguments shown in the previous section.\nDon't do this when using a reverse proxy setup, otherwise it will be\npossible to bypass the proxy.\n\n``0.0.0.0`` is not a valid address to navigate to, you'd use a specific\nIP address in your browser.\n"},{"id":190,"name":"tests/templates/nested","nodeType":"Package"},{"id":191,"name":"nested.txt","nodeType":"TextFile","path":"tests/templates/nested","text":"I'm nested\n"},{"className":"IntEnum","col":0,"comment":"null","endLoc":225,"id":192,"nodeType":"Class","startLoc":221,"text":"class IntEnum(int, _IntEnumBase):\n _value_: int\n @_magic_enum_attr\n def value(self) -> int: ...\n def __new__(cls, value: int) -> Self: ..."},{"id":193,"name":"config.yml","nodeType":"TextFile","path":".github/ISSUE_TEMPLATE","text":"blank_issues_enabled: false\ncontact_links:\n - name: Security issue\n url: security@palletsprojects.com\n about: Do not report security issues publicly. Email our security contact.\n - name: Questions\n url: https://stackoverflow.com/questions/tagged/flask?tab=Frequent\n about: Search for and ask questions about your code on Stack Overflow.\n - name: Questions and discussions\n url: https://discord.gg/pallets\n about: Discuss questions about your code on our Discord chat.\n"},{"col":4,"comment":"null","endLoc":1933,"header":"def __init__(self, *args: object) -> None","id":194,"name":"__init__","nodeType":"Function","startLoc":1933,"text":"def __init__(self, *args: object) -> None: ..."},{"fileName":"test_blog.py","filePath":"examples/tutorial/tests","id":197,"nodeType":"File","text":"import pytest\n\nfrom flaskr.db import get_db\n\n\ndef test_index(client, auth):\n response = client.get(\"/\")\n assert b\"Log In\" in response.data\n assert b\"Register\" in response.data\n\n auth.login()\n response = client.get(\"/\")\n assert b\"test title\" in response.data\n assert b\"by test on 2018-01-01\" in response.data\n assert b\"test\\nbody\" in response.data\n assert b'href=\"/1/update\"' in response.data\n\n\n@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\", \"/1/delete\"))\ndef test_login_required(client, path):\n response = client.post(path)\n assert response.headers[\"Location\"] == \"/auth/login\"\n\n\ndef test_author_required(app, client, auth):\n # change the post author to another user\n with app.app_context():\n db = get_db()\n db.execute(\"UPDATE post SET author_id = 2 WHERE id = 1\")\n db.commit()\n\n auth.login()\n # current user can't modify other user's post\n assert client.post(\"/1/update\").status_code == 403\n assert client.post(\"/1/delete\").status_code == 403\n # current user doesn't see edit link\n assert b'href=\"/1/update\"' not in client.get(\"/\").data\n\n\n@pytest.mark.parametrize(\"path\", (\"/2/update\", \"/2/delete\"))\ndef test_exists_required(client, auth, path):\n auth.login()\n assert client.post(path).status_code == 404\n\n\ndef test_create(client, auth, app):\n auth.login()\n assert client.get(\"/create\").status_code == 200\n client.post(\"/create\", data={\"title\": \"created\", \"body\": \"\"})\n\n with app.app_context():\n db = get_db()\n count = db.execute(\"SELECT COUNT(id) FROM post\").fetchone()[0]\n assert count == 2\n\n\ndef test_update(client, auth, app):\n auth.login()\n assert client.get(\"/1/update\").status_code == 200\n client.post(\"/1/update\", data={\"title\": \"updated\", \"body\": \"\"})\n\n with app.app_context():\n db = get_db()\n post = db.execute(\"SELECT * FROM post WHERE id = 1\").fetchone()\n assert post[\"title\"] == \"updated\"\n\n\n@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\"))\ndef test_create_update_validate(client, auth, path):\n auth.login()\n response = client.post(path, data={\"title\": \"\", \"body\": \"\"})\n assert b\"Title is required.\" in response.data\n\n\ndef test_delete(client, auth, app):\n auth.login()\n response = client.post(\"/1/delete\")\n assert response.headers[\"Location\"] == \"/\"\n\n with app.app_context():\n db = get_db()\n post = db.execute(\"SELECT * FROM post WHERE id = 1\").fetchone()\n assert post is None\n"},{"col":0,"comment":"null","endLoc":16,"header":"def test_index(client, auth)","id":198,"name":"test_index","nodeType":"Function","startLoc":6,"text":"def test_index(client, auth):\n response = client.get(\"/\")\n assert b\"Log In\" in response.data\n assert b\"Register\" in response.data\n\n auth.login()\n response = client.get(\"/\")\n assert b\"test title\" in response.data\n assert b\"by test on 2018-01-01\" in response.data\n assert b\"test\\nbody\" in response.data\n assert b'href=\"/1/update\"' in response.data"},{"id":199,"name":"streaming.rst","nodeType":"TextFile","path":"docs/patterns","text":"Streaming Contents\n==================\n\nSometimes you want to send an enormous amount of data to the client, much\nmore than you want to keep in memory. When you are generating the data on\nthe fly though, how do you send that back to the client without the\nroundtrip to the filesystem?\n\nThe answer is by using generators and direct responses.\n\nBasic Usage\n-----------\n\nThis is a basic view function that generates a lot of CSV data on the fly.\nThe trick is to have an inner function that uses a generator to generate\ndata and to then invoke that function and pass it to a response object::\n\n @app.route('/large.csv')\n def generate_large_csv():\n def generate():\n for row in iter_all_rows():\n yield f\"{','.join(row)}\\n\"\n return generate(), {\"Content-Type\": \"text/csv\"}\n\nEach ``yield`` expression is directly sent to the browser. Note though\nthat some WSGI middlewares might break streaming, so be careful there in\ndebug environments with profilers and other things you might have enabled.\n\nStreaming from Templates\n------------------------\n\nThe Jinja2 template engine supports rendering a template piece by\npiece, returning an iterator of strings. Flask provides the\n:func:`~flask.stream_template` and :func:`~flask.stream_template_string`\nfunctions to make this easier to use.\n\n.. code-block:: python\n\n from flask import stream_template\n\n @app.get(\"/timeline\")\n def timeline():\n return stream_template(\"timeline.html\")\n\nThe parts yielded by the render stream tend to match statement blocks in\nthe template.\n\n\nStreaming with Context\n----------------------\n\nThe :data:`~flask.request` will not be active while the generator is\nrunning, because the view has already returned at that point. If you try\nto access ``request``, you'll get a ``RuntimeError``.\n\nIf your generator function relies on data in ``request``, use the\n:func:`~flask.stream_with_context` wrapper. This will keep the request\ncontext active during the generator.\n\n.. code-block:: python\n\n from flask import stream_with_context, request\n from markupsafe import escape\n\n @app.route('/stream')\n def streamed_response():\n def generate():\n yield '

Hello '\n yield escape(request.args['name'])\n yield '!

'\n return stream_with_context(generate())\n\nIt can also be used as a decorator.\n\n.. code-block:: python\n\n @stream_with_context\n def generate():\n ...\n\n return generate()\n\nThe :func:`~flask.stream_template` and\n:func:`~flask.stream_template_string` functions automatically\nuse :func:`~flask.stream_with_context` if a request is active.\n"},{"className":"IntEnum","col":0,"comment":"null","endLoc":225,"id":200,"nodeType":"Class","startLoc":221,"text":"class IntEnum(int, _IntEnumBase):\n _value_: int\n @_magic_enum_attr\n def value(self) -> int: ...\n def __new__(cls, value: int) -> Self: ..."},{"className":"defaultdict","col":0,"comment":"null","endLoc":416,"id":201,"nodeType":"Class","startLoc":377,"text":"class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]):\n default_factory: Callable[[], _VT] | None\n @overload\n def __init__(self) -> None: ...\n @overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ...\n @overload\n def __init__(self, __default_factory: Callable[[], _VT] | None) -> None: ...\n @overload\n def __init__(self: defaultdict[str, _VT], __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ...\n @overload\n def __init__(self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT],\n __default_factory: Callable[[], _VT] | None,\n __map: SupportsKeysAndGetItem[str, _VT],\n **kwargs: _VT,\n ) -> None: ...\n @overload\n def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ...\n @overload\n def __init__(\n self: defaultdict[str, _VT],\n __default_factory: Callable[[], _VT] | None,\n __iterable: Iterable[tuple[str, _VT]],\n **kwargs: _VT,\n ) -> None: ...\n def __missing__(self, __key: _KT) -> _VT: ...\n def __copy__(self) -> Self: ...\n def copy(self) -> Self: ...\n if sys.version_info >= (3, 9):\n @overload\n def __or__(self, __value: dict[_KT, _VT]) -> Self: ...\n @overload\n def __or__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ...\n @overload\n def __ror__(self, __value: dict[_KT, _VT]) -> Self: ...\n @overload\n def __ror__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"fileName":"test_reqctx.py","filePath":"tests","id":202,"nodeType":"File","text":"import warnings\n\nimport pytest\n\nimport flask\nfrom flask.globals import request_ctx\nfrom flask.sessions import SecureCookieSessionInterface\nfrom flask.sessions import SessionInterface\n\ntry:\n from greenlet import greenlet\nexcept ImportError:\n greenlet = None\n\n\ndef test_teardown_on_pop(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n ctx = app.test_request_context()\n ctx.push()\n assert buffer == []\n ctx.pop()\n assert buffer == [None]\n\n\ndef test_teardown_with_previous_exception(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n\n with app.test_request_context():\n assert buffer == []\n assert buffer == [None]\n\n\ndef test_teardown_with_handled_exception(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n with app.test_request_context():\n assert buffer == []\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n assert buffer == [None]\n\n\ndef test_proper_test_request_context(app):\n app.config.update(SERVER_NAME=\"localhost.localdomain:5000\")\n\n @app.route(\"/\")\n def index():\n return None\n\n @app.route(\"/\", subdomain=\"foo\")\n def sub():\n return None\n\n with app.test_request_context(\"/\"):\n assert (\n flask.url_for(\"index\", _external=True)\n == \"http://localhost.localdomain:5000/\"\n )\n\n with app.test_request_context(\"/\"):\n assert (\n flask.url_for(\"sub\", _external=True)\n == \"http://foo.localhost.localdomain:5000/\"\n )\n\n # suppress Werkzeug 0.15 warning about name mismatch\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\", \"Current server name\", UserWarning, \"flask.app\"\n )\n with app.test_request_context(\n \"/\", environ_overrides={\"HTTP_HOST\": \"localhost\"}\n ):\n pass\n\n app.config.update(SERVER_NAME=\"localhost\")\n with app.test_request_context(\"/\", environ_overrides={\"SERVER_NAME\": \"localhost\"}):\n pass\n\n app.config.update(SERVER_NAME=\"localhost:80\")\n with app.test_request_context(\n \"/\", environ_overrides={\"SERVER_NAME\": \"localhost:80\"}\n ):\n pass\n\n\ndef test_context_binding(app):\n @app.route(\"/\")\n def index():\n return f\"Hello {flask.request.args['name']}!\"\n\n @app.route(\"/meh\")\n def meh():\n return flask.request.url\n\n with app.test_request_context(\"/?name=World\"):\n assert index() == \"Hello World!\"\n with app.test_request_context(\"/meh\"):\n assert meh() == \"http://localhost/meh\"\n assert not flask.request\n\n\ndef test_context_test(app):\n assert not flask.request\n assert not flask.has_request_context()\n ctx = app.test_request_context()\n ctx.push()\n try:\n assert flask.request\n assert flask.has_request_context()\n finally:\n ctx.pop()\n\n\ndef test_manual_context_binding(app):\n @app.route(\"/\")\n def index():\n return f\"Hello {flask.request.args['name']}!\"\n\n ctx = app.test_request_context(\"/?name=World\")\n ctx.push()\n assert index() == \"Hello World!\"\n ctx.pop()\n with pytest.raises(RuntimeError):\n index()\n\n\n@pytest.mark.skipif(greenlet is None, reason=\"greenlet not installed\")\nclass TestGreenletContextCopying:\n def test_greenlet_context_copying(self, app, client):\n greenlets = []\n\n @app.route(\"/\")\n def index():\n flask.session[\"fizz\"] = \"buzz\"\n reqctx = request_ctx.copy()\n\n def g():\n assert not flask.request\n assert not flask.current_app\n with reqctx:\n assert flask.request\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session.get(\"fizz\") == \"buzz\"\n assert not flask.request\n return 42\n\n greenlets.append(greenlet(g))\n return \"Hello World!\"\n\n rv = client.get(\"/?foo=bar\")\n assert rv.data == b\"Hello World!\"\n\n result = greenlets[0].run()\n assert result == 42\n\n def test_greenlet_context_copying_api(self, app, client):\n greenlets = []\n\n @app.route(\"/\")\n def index():\n flask.session[\"fizz\"] = \"buzz\"\n\n @flask.copy_current_request_context\n def g():\n assert flask.request\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session.get(\"fizz\") == \"buzz\"\n return 42\n\n greenlets.append(greenlet(g))\n return \"Hello World!\"\n\n rv = client.get(\"/?foo=bar\")\n assert rv.data == b\"Hello World!\"\n\n result = greenlets[0].run()\n assert result == 42\n\n\ndef test_session_error_pops_context():\n class SessionError(Exception):\n pass\n\n class FailingSessionInterface(SessionInterface):\n def open_session(self, app, request):\n raise SessionError()\n\n class CustomFlask(flask.Flask):\n session_interface = FailingSessionInterface()\n\n app = CustomFlask(__name__)\n\n @app.route(\"/\")\n def index():\n # shouldn't get here\n AssertionError()\n\n response = app.test_client().get(\"/\")\n assert response.status_code == 500\n assert not flask.request\n assert not flask.current_app\n\n\ndef test_session_dynamic_cookie_name():\n # This session interface will use a cookie with a different name if the\n # requested url ends with the string \"dynamic_cookie\"\n class PathAwareSessionInterface(SecureCookieSessionInterface):\n def get_cookie_name(self, app):\n if flask.request.url.endswith(\"dynamic_cookie\"):\n return \"dynamic_cookie_name\"\n else:\n return super().get_cookie_name(app)\n\n class CustomFlask(flask.Flask):\n session_interface = PathAwareSessionInterface()\n\n app = CustomFlask(__name__)\n app.secret_key = \"secret_key\"\n\n @app.route(\"/set\", methods=[\"POST\"])\n def set():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\"\n\n @app.route(\"/get\")\n def get():\n v = flask.session.get(\"value\", \"None\")\n return v\n\n @app.route(\"/set_dynamic_cookie\", methods=[\"POST\"])\n def set_dynamic_cookie():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\"\n\n @app.route(\"/get_dynamic_cookie\")\n def get_dynamic_cookie():\n v = flask.session.get(\"value\", \"None\")\n return v\n\n test_client = app.test_client()\n\n # first set the cookie in both /set urls but each with a different value\n assert test_client.post(\"/set\", data={\"value\": \"42\"}).data == b\"value set\"\n assert (\n test_client.post(\"/set_dynamic_cookie\", data={\"value\": \"616\"}).data\n == b\"value set\"\n )\n\n # now check that the relevant values come back - meaning that different\n # cookies are being used for the urls that end with \"dynamic cookie\"\n assert test_client.get(\"/get\").data == b\"42\"\n assert test_client.get(\"/get_dynamic_cookie\").data == b\"616\"\n\n\ndef test_bad_environ_raises_bad_request():\n app = flask.Flask(__name__)\n\n from flask.testing import EnvironBuilder\n\n builder = EnvironBuilder(app)\n environ = builder.get_environ()\n\n # use a non-printable character in the Host - this is key to this test\n environ[\"HTTP_HOST\"] = \"\\x8a\"\n\n with app.request_context(environ):\n response = app.full_dispatch_request()\n assert response.status_code == 400\n\n\ndef test_environ_for_valid_idna_completes():\n app = flask.Flask(__name__)\n\n @app.route(\"/\")\n def index():\n return \"Hello World!\"\n\n from flask.testing import EnvironBuilder\n\n builder = EnvironBuilder(app)\n environ = builder.get_environ()\n\n # these characters are all IDNA-compatible\n environ[\"HTTP_HOST\"] = \"ąśźäüжŠßя.com\"\n\n with app.request_context(environ):\n response = app.full_dispatch_request()\n\n assert response.status_code == 200\n\n\ndef test_normal_environ_completes():\n app = flask.Flask(__name__)\n\n @app.route(\"/\")\n def index():\n return \"Hello World!\"\n\n response = app.test_client().get(\"/\", headers={\"host\": \"xn--on-0ia.com\"})\n assert response.status_code == 200\n"},{"id":203,"name":"tests.txt","nodeType":"TextFile","path":"requirements","text":"# SHA1:3c8dde35aba20388b22430b17974af8ef8205b4f\n#\n# This file is autogenerated by pip-compile-multi\n# To update, run:\n#\n# pip-compile-multi\n#\nasgiref==3.6.0\n # via -r requirements/tests.in\niniconfig==2.0.0\n # via pytest\npackaging==23.0\n # via pytest\npluggy==1.0.0\n # via pytest\npytest==7.3.0\n # via -r requirements/tests.in\npython-dotenv==1.0.0 ; python_version >= \"3.8\"\n # via -r requirements/tests.in\n"},{"className":"FakePath","col":0,"comment":"Fake object to represent a ``PathLike object``.\n\n This represents a ``pathlib.Path`` object in python 3.\n See: https://www.python.org/dev/peps/pep-0519/\n ","endLoc":22,"id":204,"nodeType":"Class","startLoc":11,"text":"class FakePath:\n \"\"\"Fake object to represent a ``PathLike object``.\n\n This represents a ``pathlib.Path`` object in python 3.\n See: https://www.python.org/dev/peps/pep-0519/\n \"\"\"\n\n def __init__(self, path):\n self.path = path\n\n def __fspath__(self):\n return self.path"},{"col":4,"comment":"null","endLoc":19,"header":"def __init__(self, path)","id":205,"name":"__init__","nodeType":"Function","startLoc":18,"text":"def __init__(self, path):\n self.path = path"},{"col":4,"comment":"null","endLoc":22,"header":"def __fspath__(self)","id":206,"name":"__fspath__","nodeType":"Function","startLoc":21,"text":"def __fspath__(self):\n return self.path"},{"attributeType":"null","col":8,"comment":"null","endLoc":19,"id":207,"name":"path","nodeType":"Attribute","startLoc":19,"text":"self.path"},{"col":0,"comment":"null","endLoc":22,"header":"@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\", \"/1/delete\"))\ndef test_login_required(client, path)","id":208,"name":"test_login_required","nodeType":"Function","startLoc":19,"text":"@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\", \"/1/delete\"))\ndef test_login_required(client, path):\n response = client.post(path)\n assert response.headers[\"Location\"] == \"/auth/login\""},{"col":4,"comment":"null","endLoc":57,"header":"def logout(self)","id":209,"name":"logout","nodeType":"Function","startLoc":56,"text":"def logout(self):\n return self._client.get(\"/auth/logout\")"},{"col":0,"comment":"null","endLoc":37,"header":"def test_author_required(app, client, auth)","id":210,"name":"test_author_required","nodeType":"Function","startLoc":25,"text":"def test_author_required(app, client, auth):\n # change the post author to another user\n with app.app_context():\n db = get_db()\n db.execute(\"UPDATE post SET author_id = 2 WHERE id = 1\")\n db.commit()\n\n auth.login()\n # current user can't modify other user's post\n assert client.post(\"/1/update\").status_code == 403\n assert client.post(\"/1/delete\").status_code == 403\n # current user doesn't see edit link\n assert b'href=\"/1/update\"' not in client.get(\"/\").data"},{"col":0,"comment":"","endLoc":1,"header":"flask.py#","id":211,"name":"","nodeType":"Function","startLoc":1,"text":"app = Flask(__name__)"},{"attributeType":"null","col":8,"comment":"null","endLoc":49,"id":212,"name":"_client","nodeType":"Attribute","startLoc":49,"text":"self._client"},{"col":0,"comment":"Create and configure a new app instance for each test.","endLoc":32,"header":"@pytest.fixture\ndef app()","id":213,"name":"app","nodeType":"Function","startLoc":15,"text":"@pytest.fixture\ndef app():\n \"\"\"Create and configure a new app instance for each test.\"\"\"\n # create a temporary file to isolate the database for each test\n db_fd, db_path = tempfile.mkstemp()\n # create the app with common test config\n app = create_app({\"TESTING\": True, \"DATABASE\": db_path})\n\n # create the database and load test data\n with app.app_context():\n init_db()\n get_db().executescript(_data_sql)\n\n yield app\n\n # close and remove the temporary database\n os.close(db_fd)\n os.unlink(db_path)"},{"id":214,"name":"dev.in","nodeType":"TextFile","path":"requirements","text":"-r docs.in\n-r tests.in\n-r typing.in\npip-compile-multi\npre-commit\ntox\n"},{"className":"PyBytesIO","col":0,"comment":"null","endLoc":30,"id":216,"nodeType":"Class","startLoc":25,"text":"class PyBytesIO:\n def __init__(self, *args, **kwargs):\n self._io = io.BytesIO(*args, **kwargs)\n\n def __getattr__(self, name):\n return getattr(self._io, name)"},{"col":4,"comment":"null","endLoc":27,"header":"def __init__(self, *args, **kwargs)","id":217,"name":"__init__","nodeType":"Function","startLoc":26,"text":"def __init__(self, *args, **kwargs):\n self._io = io.BytesIO(*args, **kwargs)"},{"col":0,"comment":"null","endLoc":43,"header":"@pytest.mark.parametrize(\"path\", (\"/2/update\", \"/2/delete\"))\ndef test_exists_required(client, auth, path)","id":218,"name":"test_exists_required","nodeType":"Function","startLoc":40,"text":"@pytest.mark.parametrize(\"path\", (\"/2/update\", \"/2/delete\"))\ndef test_exists_required(client, auth, path):\n auth.login()\n assert client.post(path).status_code == 404"},{"className":"TextIOWrapper","col":0,"comment":"null","endLoc":181,"id":219,"nodeType":"Class","startLoc":147,"text":"class TextIOWrapper(TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes\n def __init__(\n self,\n buffer: IO[bytes],\n encoding: str | None = ...,\n errors: str | None = ...,\n newline: str | None = ...,\n line_buffering: bool = ...,\n write_through: bool = ...,\n ) -> None: ...\n @property\n def buffer(self) -> BinaryIO: ...\n @property\n def closed(self) -> bool: ...\n @property\n def line_buffering(self) -> bool: ...\n @property\n def write_through(self) -> bool: ...\n def reconfigure(\n self,\n *,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool | None = None,\n write_through: bool | None = None,\n ) -> None: ...\n # These are inherited from TextIOBase, but must exist in the stub to satisfy mypy.\n def __enter__(self) -> Self: ...\n def __iter__(self) -> Iterator[str]: ... # type: ignore[override]\n def __next__(self) -> str: ... # type: ignore[override]\n def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override]\n def readline(self, __size: int = -1) -> str: ... # type: ignore[override]\n def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override]\n def seek(self, __cookie: int, __whence: int = 0) -> int: ... # stubtest needs this"},{"className":"TextIOBase","col":0,"comment":"null","endLoc":145,"id":221,"nodeType":"Class","startLoc":134,"text":"class TextIOBase(IOBase):\n encoding: str\n errors: str | None\n newlines: str | tuple[str, ...] | None\n def __iter__(self) -> Iterator[str]: ... # type: ignore[override]\n def __next__(self) -> str: ... # type: ignore[override]\n def detach(self) -> BinaryIO: ...\n def write(self, __s: str) -> int: ...\n def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override]\n def readline(self, __size: int = ...) -> str: ... # type: ignore[override]\n def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override]\n def read(self, __size: int | None = ...) -> str: ..."},{"col":0,"comment":"null","endLoc":32,"header":"@bp.post(\"/block\")\ndef block() -> dict[str, object]","id":222,"name":"block","nodeType":"Function","startLoc":29,"text":"@bp.post(\"/block\")\ndef block() -> dict[str, object]:\n result = tasks.block.delay()\n return {\"result_id\": result.id}"},{"className":"IOBase","col":0,"comment":"null","endLoc":76,"id":223,"nodeType":"Class","startLoc":51,"text":"class IOBase(metaclass=abc.ABCMeta):\n def __iter__(self) -> Iterator[bytes]: ...\n def __next__(self) -> bytes: ...\n def __enter__(self) -> Self: ...\n def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None: ...\n def close(self) -> None: ...\n def fileno(self) -> int: ...\n def flush(self) -> None: ...\n def isatty(self) -> bool: ...\n def readable(self) -> bool: ...\n read: Callable[..., Any]\n def readlines(self, __hint: int = -1) -> list[bytes]: ...\n def seek(self, __offset: int, __whence: int = ...) -> int: ...\n def seekable(self) -> bool: ...\n def tell(self) -> int: ...\n def truncate(self, __size: int | None = ...) -> int: ...\n def writable(self) -> bool: ...\n write: Callable[..., Any]\n def writelines(self, __lines: Iterable[ReadableBuffer]) -> None: ...\n def readline(self, __size: int | None = -1) -> bytes: ...\n def __del__(self) -> None: ...\n @property\n def closed(self) -> bool: ...\n def _checkClosed(self, msg: str | None = ...) -> None: ... # undocumented"},{"col":4,"comment":"null","endLoc":52,"header":"def __iter__(self) -> Iterator[bytes]","id":224,"name":"__iter__","nodeType":"Function","startLoc":52,"text":"def __iter__(self) -> Iterator[bytes]: ..."},{"col":4,"comment":"null","endLoc":53,"header":"def __next__(self) -> bytes","id":225,"name":"__next__","nodeType":"Function","startLoc":53,"text":"def __next__(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":54,"header":"def __enter__(self) -> Self","id":226,"name":"__enter__","nodeType":"Function","startLoc":54,"text":"def __enter__(self) -> Self: ..."},{"col":0,"comment":"null","endLoc":54,"header":"def test_create(client, auth, app)","id":227,"name":"test_create","nodeType":"Function","startLoc":46,"text":"def test_create(client, auth, app):\n auth.login()\n assert client.get(\"/create\").status_code == 200\n client.post(\"/create\", data={\"title\": \"created\", \"body\": \"\"})\n\n with app.app_context():\n db = get_db()\n count = db.execute(\"SELECT COUNT(id) FROM post\").fetchone()[0]\n assert count == 2"},{"col":4,"comment":"null","endLoc":57,"header":"def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None","id":228,"name":"__exit__","nodeType":"Function","startLoc":55,"text":"def __exit__(\n self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":58,"header":"def close(self) -> None","id":229,"name":"close","nodeType":"Function","startLoc":58,"text":"def close(self) -> None: ..."},{"col":4,"comment":"null","endLoc":59,"header":"def fileno(self) -> int","id":230,"name":"fileno","nodeType":"Function","startLoc":59,"text":"def fileno(self) -> int: ..."},{"col":4,"comment":"null","endLoc":60,"header":"def flush(self) -> None","id":231,"name":"flush","nodeType":"Function","startLoc":60,"text":"def flush(self) -> None: ..."},{"col":0,"comment":"Find the most appropriate error stream for the application. If a request\n is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.\n\n If you configure your own :class:`logging.StreamHandler`, you may want to\n use this for the stream. If you are using file or dict configuration and\n can't import this directly, you can refer to it as\n ``ext://flask.logging.wsgi_errors_stream``.\n ","endLoc":23,"header":"@LocalProxy\ndef wsgi_errors_stream() -> t.TextIO","id":232,"name":"wsgi_errors_stream","nodeType":"Function","startLoc":13,"text":"@LocalProxy\ndef wsgi_errors_stream() -> t.TextIO:\n \"\"\"Find the most appropriate error stream for the application. If a request\n is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.\n\n If you configure your own :class:`logging.StreamHandler`, you may want to\n use this for the stream. If you are using file or dict configuration and\n can't import this directly, you can refer to it as\n ``ext://flask.logging.wsgi_errors_stream``.\n \"\"\"\n return request.environ[\"wsgi.errors\"] if request else sys.stderr"},{"col":4,"comment":"null","endLoc":61,"header":"def isatty(self) -> bool","id":233,"name":"isatty","nodeType":"Function","startLoc":61,"text":"def isatty(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":62,"header":"def readable(self) -> bool","id":234,"name":"readable","nodeType":"Function","startLoc":62,"text":"def readable(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":64,"header":"def readlines(self, __hint: int = -1) -> list[bytes]","id":235,"name":"readlines","nodeType":"Function","startLoc":64,"text":"def readlines(self, __hint: int = -1) -> list[bytes]: ..."},{"col":0,"comment":"Check if there is a handler in the logging chain that will handle the\n given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.\n ","endLoc":42,"header":"def has_level_handler(logger: logging.Logger) -> bool","id":236,"name":"has_level_handler","nodeType":"Function","startLoc":26,"text":"def has_level_handler(logger: logging.Logger) -> bool:\n \"\"\"Check if there is a handler in the logging chain that will handle the\n given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.\n \"\"\"\n level = logger.getEffectiveLevel()\n current = logger\n\n while current:\n if any(handler.level <= level for handler in current.handlers):\n return True\n\n if not current.propagate:\n break\n\n current = current.parent # type: ignore\n\n return False"},{"col":4,"comment":"null","endLoc":65,"header":"def seek(self, __offset: int, __whence: int = ...) -> int","id":237,"name":"seek","nodeType":"Function","startLoc":65,"text":"def seek(self, __offset: int, __whence: int = ...) -> int: ..."},{"col":4,"comment":"null","endLoc":66,"header":"def seekable(self) -> bool","id":238,"name":"seekable","nodeType":"Function","startLoc":66,"text":"def seekable(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":67,"header":"def tell(self) -> int","id":239,"name":"tell","nodeType":"Function","startLoc":67,"text":"def tell(self) -> int: ..."},{"col":0,"comment":"null","endLoc":65,"header":"def test_update(client, auth, app)","id":240,"name":"test_update","nodeType":"Function","startLoc":57,"text":"def test_update(client, auth, app):\n auth.login()\n assert client.get(\"/1/update\").status_code == 200\n client.post(\"/1/update\", data={\"title\": \"updated\", \"body\": \"\"})\n\n with app.app_context():\n db = get_db()\n post = db.execute(\"SELECT * FROM post WHERE id = 1\").fetchone()\n assert post[\"title\"] == \"updated\""},{"col":4,"comment":"null","endLoc":1100,"header":"@overload # type: ignore[override]\n def get(self, __key: _KT) -> _VT | None","id":241,"name":"get","nodeType":"Function","startLoc":1099,"text":"@overload # type: ignore[override]\n def get(self, __key: _KT) -> _VT | None: ..."},{"col":4,"comment":"null","endLoc":68,"header":"def truncate(self, __size: int | None = ...) -> int","id":242,"name":"truncate","nodeType":"Function","startLoc":68,"text":"def truncate(self, __size: int | None = ...) -> int: ..."},{"col":4,"comment":"null","endLoc":69,"header":"def writable(self) -> bool","id":243,"name":"writable","nodeType":"Function","startLoc":69,"text":"def writable(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":71,"header":"def writelines(self, __lines: Iterable[ReadableBuffer]) -> None","id":244,"name":"writelines","nodeType":"Function","startLoc":71,"text":"def writelines(self, __lines: Iterable[ReadableBuffer]) -> None: ..."},{"col":4,"comment":"null","endLoc":72,"header":"def readline(self, __size: int | None = -1) -> bytes","id":245,"name":"readline","nodeType":"Function","startLoc":72,"text":"def readline(self, __size: int | None = -1) -> bytes: ..."},{"col":4,"comment":"null","endLoc":73,"header":"def __del__(self) -> None","id":246,"name":"__del__","nodeType":"Function","startLoc":73,"text":"def __del__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":75,"header":"@property\n def closed(self) -> bool","id":247,"name":"closed","nodeType":"Function","startLoc":74,"text":"@property\n def closed(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":76,"header":"def _checkClosed(self, msg: str | None = ...) -> None","id":248,"name":"_checkClosed","nodeType":"Function","startLoc":76,"text":"def _checkClosed(self, msg: str | None = ...) -> None: ... # undocumented"},{"attributeType":"(...) -> Any","col":4,"comment":"null","endLoc":63,"id":249,"name":"read","nodeType":"Attribute","startLoc":63,"text":"read"},{"col":0,"comment":"null","endLoc":72,"header":"@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\"))\ndef test_create_update_validate(client, auth, path)","id":250,"name":"test_create_update_validate","nodeType":"Function","startLoc":68,"text":"@pytest.mark.parametrize(\"path\", (\"/create\", \"/1/update\"))\ndef test_create_update_validate(client, auth, path):\n auth.login()\n response = client.post(path, data={\"title\": \"\", \"body\": \"\"})\n assert b\"Title is required.\" in response.data"},{"col":4,"comment":"null","endLoc":68,"header":"@overload\n def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]","id":251,"name":"lru_cache","nodeType":"Function","startLoc":67,"text":"@overload\n def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ..."},{"col":0,"comment":"null","endLoc":38,"header":"@bp.post(\"/process\")\ndef process() -> dict[str, object]","id":252,"name":"process","nodeType":"Function","startLoc":35,"text":"@bp.post(\"/process\")\ndef process() -> dict[str, object]:\n result = tasks.process.delay(total=request.form.get(\"total\", type=int))\n return {\"result_id\": result.id}"},{"id":253,"name":"lifecycle.rst","nodeType":"TextFile","path":"docs","text":"Application Structure and Lifecycle\n===================================\n\nFlask makes it pretty easy to write a web application. But there are quite a few\ndifferent parts to an application and to each request it handles. Knowing what happens\nduring application setup, serving, and handling requests will help you know what's\npossible in Flask and how to structure your application.\n\n\nApplication Setup\n-----------------\n\nThe first step in creating a Flask application is creating the application object. Each\nFlask application is an instance of the :class:`.Flask` class, which collects all\nconfiguration, extensions, and views.\n\n.. code-block:: python\n\n from flask import Flask\n\n app = Flask(__name__)\n app.config.from_mapping(\n SECRET_KEY=\"dev\",\n )\n app.config.from_prefixed_env()\n\n @app.route(\"/\")\n def index():\n return \"Hello, World!\"\n\nThis is known as the \"application setup phase\", it's the code you write that's outside\nany view functions or other handlers. It can be split up between different modules and\nsub-packages, but all code that you want to be part of your application must be imported\nin order for it to be registered.\n\nAll application setup must be completed before you start serving your application and\nhandling requests. This is because WSGI servers divide work between multiple workers, or\ncan be distributed across multiple machines. If the configuration changed in one worker,\nthere's no way for Flask to ensure consistency between other workers.\n\nFlask tries to help developers catch some of these setup ordering issues by showing an\nerror if setup-related methods are called after requests are handled. In that case\nyou'll see this error:\n\n The setup method 'route' can no longer be called on the application. It has already\n handled its first request, any changes will not be applied consistently.\n Make sure all imports, decorators, functions, etc. needed to set up the application\n are done before running it.\n\nHowever, it is not possible for Flask to detect all cases of out-of-order setup. In\ngeneral, don't do anything to modify the ``Flask`` app object and ``Blueprint`` objects\nfrom within view functions that run during requests. This includes:\n\n- Adding routes, view functions, and other request handlers with ``@app.route``,\n ``@app.errorhandler``, ``@app.before_request``, etc.\n- Registering blueprints.\n- Loading configuration with ``app.config``.\n- Setting up the Jinja template environment with ``app.jinja_env``.\n- Setting a session interface, instead of the default itsdangerous cookie.\n- Setting a JSON provider with ``app.json``, instead of the default provider.\n- Creating and initializing Flask extensions.\n\n\nServing the Application\n-----------------------\n\nFlask is a WSGI application framework. The other half of WSGI is the WSGI server. During\ndevelopment, Flask, through Werkzeug, provides a development WSGI server with the\n``flask run`` CLI command. When you are done with development, use a production server\nto serve your application, see :doc:`deploying/index`.\n\nRegardless of what server you're using, it will follow the :pep:`3333` WSGI spec. The\nWSGI server will be told how to access your Flask application object, which is the WSGI\napplication. Then it will start listening for HTTP requests, translate the request data\ninto a WSGI environ, and call the WSGI application with that data. The WSGI application\nwill return data that is translated into an HTTP response.\n\n#. Browser or other client makes HTTP request.\n#. WSGI server receives request.\n#. WSGI server converts HTTP data to WSGI ``environ`` dict.\n#. WSGI server calls WSGI application with the ``environ``.\n#. Flask, the WSGI application, does all its internal processing to route the request\n to a view function, handle errors, etc.\n#. Flask translates View function return into WSGI response data, passes it to WSGI\n server.\n#. WSGI server creates and send an HTTP response.\n#. Client receives the HTTP response.\n\n\nMiddleware\n~~~~~~~~~~\n\nThe WSGI application above is a callable that behaves in a certain way. Middleware\nis a WSGI application that wraps another WSGI application. It's a similar concept to\nPython decorators. The outermost middleware will be called by the server. It can modify\nthe data passed to it, then call the WSGI application (or further middleware) that it\nwraps, and so on. And it can take the return value of that call and modify it further.\n\nFrom the WSGI server's perspective, there is one WSGI application, the one it calls\ndirectly. Typically, Flask is the \"real\" application at the end of the chain of\nmiddleware. But even Flask can call further WSGI applications, although that's an\nadvanced, uncommon use case.\n\nA common middleware you'll see used with Flask is Werkzeug's\n:class:`~werkzeug.middleware.proxy_fix.ProxyFix`, which modifies the request to look\nlike it came directly from a client even if it passed through HTTP proxies on the way.\nThere are other middleware that can handle serving static files, authentication, etc.\n\n\nHow a Request is Handled\n------------------------\n\nFor us, the interesting part of the steps above is when Flask gets called by the WSGI\nserver (or middleware). At that point, it will do quite a lot to handle the request and\ngenerate the response. At the most basic, it will match the URL to a view function, call\nthe view function, and pass the return value back to the server. But there are many more\nparts that you can use to customize its behavior.\n\n#. WSGI server calls the Flask object, which calls :meth:`.Flask.wsgi_app`.\n#. A :class:`.RequestContext` object is created. This converts the WSGI ``environ``\n dict into a :class:`.Request` object. It also creates an :class:`AppContext` object.\n#. The :doc:`app context ` is pushed, which makes :data:`.current_app` and\n :data:`.g` available.\n#. The :data:`.appcontext_pushed` signal is sent.\n#. The :doc:`request context ` is pushed, which makes :attr:`.request` and\n :class:`.session` available.\n#. The session is opened, loading any existing session data using the app's\n :attr:`~.Flask.session_interface`, an instance of :class:`.SessionInterface`.\n#. The URL is matched against the URL rules registered with the :meth:`~.Flask.route`\n decorator during application setup. If there is no match, the error - usually a 404,\n 405, or redirect - is stored to be handled later.\n#. The :data:`.request_started` signal is sent.\n#. Any :meth:`~.Flask.url_value_preprocessor` decorated functions are called.\n#. Any :meth:`~.Flask.before_request` decorated functions are called. If any of\n these function returns a value it is treated as the response immediately.\n#. If the URL didn't match a route a few steps ago, that error is raised now.\n#. The :meth:`~.Flask.route` decorated view function associated with the matched URL\n is called and returns a value to be used as the response.\n#. If any step so far raised an exception, and there is an :meth:`~.Flask.errorhandler`\n decorated function that matches the exception class or HTTP error code, it is\n called to handle the error and return a response.\n#. Whatever returned a response value - a before request function, the view, or an\n error handler, that value is converted to a :class:`.Response` object.\n#. Any :func:`~.after_this_request` decorated functions are called, then cleared.\n#. Any :meth:`~.Flask.after_request` decorated functions are called, which can modify\n the response object.\n#. The session is saved, persisting any modified session data using the app's\n :attr:`~.Flask.session_interface`.\n#. The :data:`.request_finished` signal is sent.\n#. If any step so far raised an exception, and it was not handled by an error handler\n function, it is handled now. HTTP exceptions are treated as responses with their\n corresponding status code, other exceptions are converted to a generic 500 response.\n The :data:`.got_request_exception` signal is sent.\n#. The response object's status, headers, and body are returned to the WSGI server.\n#. Any :meth:`~.Flask.teardown_request` decorated functions are called.\n#. The :data:`.request_tearing_down` signal is sent.\n#. The request context is popped, :attr:`.request` and :class:`.session` are no longer\n available.\n#. Any :meth:`~.Flask.teardown_appcontext` decorated functions are called.\n#. The :data:`.appcontext_tearing_down` signal is sent.\n#. The app context is popped, :data:`.current_app` and :data:`.g` are no longer\n available.\n#. The :data:`.appcontext_popped` signal is sent.\n\nThere are even more decorators and customization points than this, but that aren't part\nof every request lifecycle. They're more specific to certain things you might use during\na request, such as templates, building URLs, or handling JSON data. See the rest of this\ndocumentation, as well as the :doc:`api` to explore further.\n"},{"col":0,"comment":"null","endLoc":83,"header":"def test_delete(client, auth, app)","id":254,"name":"test_delete","nodeType":"Function","startLoc":75,"text":"def test_delete(client, auth, app):\n auth.login()\n response = client.post(\"/1/delete\")\n assert response.headers[\"Location\"] == \"/\"\n\n with app.app_context():\n db = get_db()\n post = db.execute(\"SELECT * FROM post WHERE id = 1\").fetchone()\n assert post is None"},{"fileName":"test_instance_config.py","filePath":"tests","id":255,"nodeType":"File","text":"import sys\n\nimport pytest\n\nimport flask\n\n\ndef test_explicit_instance_paths(modules_tmpdir):\n with pytest.raises(ValueError) as excinfo:\n flask.Flask(__name__, instance_path=\"instance\")\n assert \"must be absolute\" in str(excinfo.value)\n\n app = flask.Flask(__name__, instance_path=str(modules_tmpdir))\n assert app.instance_path == str(modules_tmpdir)\n\n\ndef test_uninstalled_module_paths(modules_tmpdir, purge_module):\n app = modules_tmpdir.join(\"config_module_app.py\").write(\n \"import os\\n\"\n \"import flask\\n\"\n \"here = os.path.abspath(os.path.dirname(__file__))\\n\"\n \"app = flask.Flask(__name__)\\n\"\n )\n purge_module(\"config_module_app\")\n\n from config_module_app import app\n\n assert app.instance_path == str(modules_tmpdir.join(\"instance\"))\n\n\ndef test_uninstalled_package_paths(modules_tmpdir, purge_module):\n app = modules_tmpdir.mkdir(\"config_package_app\")\n init = app.join(\"__init__.py\")\n init.write(\n \"import os\\n\"\n \"import flask\\n\"\n \"here = os.path.abspath(os.path.dirname(__file__))\\n\"\n \"app = flask.Flask(__name__)\\n\"\n )\n purge_module(\"config_package_app\")\n\n from config_package_app import app\n\n assert app.instance_path == str(modules_tmpdir.join(\"instance\"))\n\n\ndef test_uninstalled_namespace_paths(tmpdir, monkeypatch, purge_module):\n def create_namespace(package):\n project = tmpdir.join(f\"project-{package}\")\n monkeypatch.syspath_prepend(str(project))\n project.join(\"namespace\").join(package).join(\"__init__.py\").write(\n \"import flask\\napp = flask.Flask(__name__)\\n\", ensure=True\n )\n return project\n\n _ = create_namespace(\"package1\")\n project2 = create_namespace(\"package2\")\n purge_module(\"namespace.package2\")\n purge_module(\"namespace\")\n\n from namespace.package2 import app\n\n assert app.instance_path == str(project2.join(\"instance\"))\n\n\ndef test_installed_module_paths(\n modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages, limit_loader\n):\n site_packages.join(\"site_app.py\").write(\n \"import flask\\napp = flask.Flask(__name__)\\n\"\n )\n purge_module(\"site_app\")\n\n from site_app import app\n\n assert app.instance_path == modules_tmpdir.join(\"var\").join(\"site_app-instance\")\n\n\ndef test_installed_package_paths(\n limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, monkeypatch\n):\n installed_path = modules_tmpdir.mkdir(\"path\")\n monkeypatch.syspath_prepend(installed_path)\n\n app = installed_path.mkdir(\"installed_package\")\n init = app.join(\"__init__.py\")\n init.write(\"import flask\\napp = flask.Flask(__name__)\")\n purge_module(\"installed_package\")\n\n from installed_package import app\n\n assert app.instance_path == modules_tmpdir.join(\"var\").join(\n \"installed_package-instance\"\n )\n\n\ndef test_prefix_package_paths(\n limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages\n):\n app = site_packages.mkdir(\"site_package\")\n init = app.join(\"__init__.py\")\n init.write(\"import flask\\napp = flask.Flask(__name__)\")\n purge_module(\"site_package\")\n\n import site_package\n\n assert site_package.app.instance_path == modules_tmpdir.join(\"var\").join(\n \"site_package-instance\"\n )\n\n\ndef test_egg_installed_paths(install_egg, modules_tmpdir, modules_tmpdir_prefix):\n modules_tmpdir.mkdir(\"site_egg\").join(\"__init__.py\").write(\n \"import flask\\n\\napp = flask.Flask(__name__)\"\n )\n install_egg(\"site_egg\")\n try:\n import site_egg\n\n assert site_egg.app.instance_path == str(\n modules_tmpdir.join(\"var/\").join(\"site_egg-instance\")\n )\n finally:\n if \"site_egg\" in sys.modules:\n del sys.modules[\"site_egg\"]\n"},{"col":0,"comment":"null","endLoc":14,"header":"def test_explicit_instance_paths(modules_tmpdir)","id":256,"name":"test_explicit_instance_paths","nodeType":"Function","startLoc":8,"text":"def test_explicit_instance_paths(modules_tmpdir):\n with pytest.raises(ValueError) as excinfo:\n flask.Flask(__name__, instance_path=\"instance\")\n assert \"must be absolute\" in str(excinfo.value)\n\n app = flask.Flask(__name__, instance_path=str(modules_tmpdir))\n assert app.instance_path == str(modules_tmpdir)"},{"attributeType":"null","col":0,"comment":"null","endLoc":7,"id":257,"name":"bp","nodeType":"Attribute","startLoc":7,"text":"bp"},{"col":0,"comment":"","endLoc":1,"header":"views.py#","id":258,"name":"","nodeType":"Function","startLoc":1,"text":"bp = Blueprint(\"tasks\", __name__, url_prefix=\"/tasks\")"},{"col":0,"comment":"If this request connected to the database, close the\n connection.\n ","endLoc":29,"header":"def close_db(e=None)","id":259,"name":"close_db","nodeType":"Function","startLoc":22,"text":"def close_db(e=None):\n \"\"\"If this request connected to the database, close the\n connection.\n \"\"\"\n db = g.pop(\"db\", None)\n\n if db is not None:\n db.close()"},{"id":260,"name":"examples/javascript/tests","nodeType":"Package"},{"fileName":"conftest.py","filePath":"examples/javascript/tests","id":261,"nodeType":"File","text":"import pytest\n\nfrom js_example import app\n\n\n@pytest.fixture(name=\"app\")\ndef fixture_app():\n app.testing = True\n yield app\n app.testing = False\n\n\n@pytest.fixture\ndef client(app):\n return app.test_client()\n"},{"id":262,"name":"on-create-command.sh","nodeType":"TextFile","path":".devcontainer","text":"#!/bin/bash\nset -e\n\npython3 -m venv .venv\n. .venv/bin/activate\npip install -U pip setuptools wheel\npip install -r requirements/dev.txt\npip install -e .\npre-commit install --install-hooks\n"},{"id":263,"name":"extensiondev.rst","nodeType":"TextFile","path":"docs","text":"Flask Extension Development\n===========================\n\n.. currentmodule:: flask\n\nExtensions are extra packages that add functionality to a Flask\napplication. While `PyPI`_ contains many Flask extensions, you may not\nfind one that fits your need. If this is the case, you can create your\nown, and publish it for others to use as well.\n\nThis guide will show how to create a Flask extension, and some of the\ncommon patterns and requirements involved. Since extensions can do\nanything, this guide won't be able to cover every possibility.\n\nThe best ways to learn about extensions are to look at how other\nextensions you use are written, and discuss with others. Discuss your\ndesign ideas with others on our `Discord Chat`_ or\n`GitHub Discussions`_.\n\nThe best extensions share common patterns, so that anyone familiar with\nusing one extension won't feel completely lost with another. This can\nonly work if collaboration happens early.\n\n\nNaming\n------\n\nA Flask extension typically has ``flask`` in its name as a prefix or\nsuffix. If it wraps another library, it should include the library name\nas well. This makes it easy to search for extensions, and makes their\npurpose clearer.\n\nA general Python packaging recommendation is that the install name from\nthe package index and the name used in ``import`` statements should be\nrelated. The import name is lowercase, with words separated by\nunderscores (``_``). The install name is either lower case or title\ncase, with words separated by dashes (``-``). If it wraps another\nlibrary, prefer using the same case as that library's name.\n\nHere are some example install and import names:\n\n- ``Flask-Name`` imported as ``flask_name``\n- ``flask-name-lower`` imported as ``flask_name_lower``\n- ``Flask-ComboName`` imported as ``flask_comboname``\n- ``Name-Flask`` imported as ``name_flask``\n\n\nThe Extension Class and Initialization\n--------------------------------------\n\nAll extensions will need some entry point that initializes the\nextension with the application. The most common pattern is to create a\nclass that represents the extension's configuration and behavior, with\nan ``init_app`` method to apply the extension instance to the given\napplication instance.\n\n.. code-block:: python\n\n class HelloExtension:\n def __init__(self, app=None):\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n app.before_request(...)\n\nIt is important that the app is not stored on the extension, don't do\n``self.app = app``. The only time the extension should have direct\naccess to an app is during ``init_app``, otherwise it should use\n:data:`current_app`.\n\nThis allows the extension to support the application factory pattern,\navoids circular import issues when importing the extension instance\nelsewhere in a user's code, and makes testing with different\nconfigurations easier.\n\n.. code-block:: python\n\n hello = HelloExtension()\n\n def create_app():\n app = Flask(__name__)\n hello.init_app(app)\n return app\n\nAbove, the ``hello`` extension instance exists independently of the\napplication. This means that other modules in a user's project can do\n``from project import hello`` and use the extension in blueprints before\nthe app exists.\n\nThe :attr:`Flask.extensions` dict can be used to store a reference to\nthe extension on the application, or some other state specific to the\napplication. Be aware that this is a single namespace, so use a name\nunique to your extension, such as the extension's name without the\n\"flask\" prefix.\n\n\nAdding Behavior\n---------------\n\nThere are many ways that an extension can add behavior. Any setup\nmethods that are available on the :class:`Flask` object can be used\nduring an extension's ``init_app`` method.\n\nA common pattern is to use :meth:`~Flask.before_request` to initialize\nsome data or a connection at the beginning of each request, then\n:meth:`~Flask.teardown_request` to clean it up at the end. This can be\nstored on :data:`g`, discussed more below.\n\nA more lazy approach is to provide a method that initializes and caches\nthe data or connection. For example, a ``ext.get_db`` method could\ncreate a database connection the first time it's called, so that a view\nthat doesn't use the database doesn't create a connection.\n\nBesides doing something before and after every view, your extension\nmight want to add some specific views as well. In this case, you could\ndefine a :class:`Blueprint`, then call :meth:`~Flask.register_blueprint`\nduring ``init_app`` to add the blueprint to the app.\n\n\nConfiguration Techniques\n------------------------\n\nThere can be multiple levels and sources of configuration for an\nextension. You should consider what parts of your extension fall into\neach one.\n\n- Configuration per application instance, through ``app.config``\n values. This is configuration that could reasonably change for each\n deployment of an application. A common example is a URL to an\n external resource, such as a database. Configuration keys should\n start with the extension's name so that they don't interfere with\n other extensions.\n- Configuration per extension instance, through ``__init__``\n arguments. This configuration usually affects how the extension\n is used, such that it wouldn't make sense to change it per\n deployment.\n- Configuration per extension instance, through instance attributes\n and decorator methods. It might be more ergonomic to assign to\n ``ext.value``, or use a ``@ext.register`` decorator to register a\n function, after the extension instance has been created.\n- Global configuration through class attributes. Changing a class\n attribute like ``Ext.connection_class`` can customize default\n behavior without making a subclass. This could be combined\n per-extension configuration to override defaults.\n- Subclassing and overriding methods and attributes. Making the API of\n the extension itself something that can be overridden provides a\n very powerful tool for advanced customization.\n\nThe :class:`~flask.Flask` object itself uses all of these techniques.\n\nIt's up to you to decide what configuration is appropriate for your\nextension, based on what you need and what you want to support.\n\nConfiguration should not be changed after the application setup phase is\ncomplete and the server begins handling requests. Configuration is\nglobal, any changes to it are not guaranteed to be visible to other\nworkers.\n\n\nData During a Request\n---------------------\n\nWhen writing a Flask application, the :data:`~flask.g` object is used to\nstore information during a request. For example the\n:doc:`tutorial ` stores a connection to a SQLite\ndatabase as ``g.db``. Extensions can also use this, with some care.\nSince ``g`` is a single global namespace, extensions must use unique\nnames that won't collide with user data. For example, use the extension\nname as a prefix, or as a namespace.\n\n.. code-block:: python\n\n # an internal prefix with the extension name\n g._hello_user_id = 2\n\n # or an internal prefix as a namespace\n from types import SimpleNamespace\n g._hello = SimpleNamespace()\n g._hello.user_id = 2\n\nThe data in ``g`` lasts for an application context. An application\ncontext is active when a request context is, or when a CLI command is\nrun. If you're storing something that should be closed, use\n:meth:`~flask.Flask.teardown_appcontext` to ensure that it gets closed\nwhen the application context ends. If it should only be valid during a\nrequest, or would not be used in the CLI outside a request, use\n:meth:`~flask.Flask.teardown_request`.\n\n\nViews and Models\n----------------\n\nYour extension views might want to interact with specific models in your\ndatabase, or some other extension or data connected to your application.\nFor example, let's consider a ``Flask-SimpleBlog`` extension that works\nwith Flask-SQLAlchemy to provide a ``Post`` model and views to write\nand read posts.\n\nThe ``Post`` model needs to subclass the Flask-SQLAlchemy ``db.Model``\nobject, but that's only available once you've created an instance of\nthat extension, not when your extension is defining its views. So how\ncan the view code, defined before the model exists, access the model?\n\nOne method could be to use :doc:`views`. During ``__init__``, create\nthe model, then create the views by passing the model to the view\nclass's :meth:`~views.View.as_view` method.\n\n.. code-block:: python\n\n class PostAPI(MethodView):\n def __init__(self, model):\n self.model = model\n\n def get(self, id):\n post = self.model.query.get(id)\n return jsonify(post.to_json())\n\n class BlogExtension:\n def __init__(self, db):\n class Post(db.Model):\n id = db.Column(primary_key=True)\n title = db.Column(db.String, nullable=False)\n\n self.post_model = Post\n\n def init_app(self, app):\n api_view = PostAPI.as_view(model=self.post_model)\n\n db = SQLAlchemy()\n blog = BlogExtension(db)\n db.init_app(app)\n blog.init_app(app)\n\nAnother technique could be to use an attribute on the extension, such as\n``self.post_model`` from above. Add the extension to ``app.extensions``\nin ``init_app``, then access\n``current_app.extensions[\"simple_blog\"].post_model`` from views.\n\nYou may also want to provide base classes so that users can provide\ntheir own ``Post`` model that conforms to the API your extension\nexpects. So they could implement ``class Post(blog.BasePost)``, then\nset it as ``blog.post_model``.\n\nAs you can see, this can get a bit complex. Unfortunately, there's no\nperfect solution here, only different strategies and tradeoffs depending\non your needs and how much customization you want to offer. Luckily,\nthis sort of resource dependency is not a common need for most\nextensions. Remember, if you need help with design, ask on our\n`Discord Chat`_ or `GitHub Discussions`_.\n\n\nRecommended Extension Guidelines\n--------------------------------\n\nFlask previously had the concept of \"approved extensions\", where the\nFlask maintainers evaluated the quality, support, and compatibility of\nthe extensions before listing them. While the list became too difficult\nto maintain over time, the guidelines are still relevant to all\nextensions maintained and developed today, as they help the Flask\necosystem remain consistent and compatible.\n\n1. An extension requires a maintainer. In the event an extension author\n would like to move beyond the project, the project should find a new\n maintainer and transfer access to the repository, documentation,\n PyPI, and any other services. The `Pallets-Eco`_ organization on\n GitHub allows for community maintenance with oversight from the\n Pallets maintainers.\n2. The naming scheme is *Flask-ExtensionName* or *ExtensionName-Flask*.\n It must provide exactly one package or module named\n ``flask_extension_name``.\n3. The extension must use an open source license. The Python web\n ecosystem tends to prefer BSD or MIT. It must be open source and\n publicly available.\n4. The extension's API must have the following characteristics:\n\n - It must support multiple applications running in the same Python\n process. Use ``current_app`` instead of ``self.app``, store\n configuration and state per application instance.\n - It must be possible to use the factory pattern for creating\n applications. Use the ``ext.init_app()`` pattern.\n\n5. From a clone of the repository, an extension with its dependencies\n must be installable in editable mode with ``pip install -e .``.\n6. It must ship tests that can be invoked with a common tool like\n ``tox -e py``, ``nox -s test`` or ``pytest``. If not using ``tox``,\n the test dependencies should be specified in a requirements file.\n The tests must be part of the sdist distribution.\n7. A link to the documentation or project website must be in the PyPI\n metadata or the readme. The documentation should use the Flask theme\n from the `Official Pallets Themes`_.\n8. The extension's dependencies should not use upper bounds or assume\n any particular version scheme, but should use lower bounds to\n indicate minimum compatibility support. For example,\n ``sqlalchemy>=1.4``.\n9. Indicate the versions of Python supported using\n ``python_requires=\">=version\"``. Flask itself supports Python >=3.7\n as of December 2021, but this will update over time.\n\n.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+Flask\n.. _Discord Chat: https://discord.gg/pallets\n.. _GitHub Discussions: https://github.com/pallets/flask/discussions\n.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/\n.. _Pallets-Eco: https://github.com/pallets-eco\n"},{"id":264,"name":"templateinheritance.rst","nodeType":"TextFile","path":"docs/patterns","text":"Template Inheritance\n====================\n\nThe most powerful part of Jinja is template inheritance. Template inheritance\nallows you to build a base \"skeleton\" template that contains all the common\nelements of your site and defines **blocks** that child templates can override.\n\nSounds complicated but is very basic. It's easiest to understand it by starting\nwith an example.\n\n\nBase Template\n-------------\n\nThis template, which we'll call :file:`layout.html`, defines a simple HTML skeleton\ndocument that you might use for a simple two-column page. It's the job of\n\"child\" templates to fill the empty blocks with content:\n\n.. sourcecode:: html+jinja\n\n \n \n \n {% block head %}\n \n {% block title %}{% endblock %} - My Webpage\n {% endblock %}\n \n \n
{% block content %}{% endblock %}
\n
\n {% block footer %}\n © Copyright 2010 by you.\n {% endblock %}\n
\n \n \n\nIn this example, the ``{% block %}`` tags define four blocks that child templates\ncan fill in. All the `block` tag does is tell the template engine that a\nchild template may override those portions of the template.\n\nChild Template\n--------------\n\nA child template might look like this:\n\n.. sourcecode:: html+jinja\n\n {% extends \"layout.html\" %}\n {% block title %}Index{% endblock %}\n {% block head %}\n {{ super() }}\n \n {% endblock %}\n {% block content %}\n

Index

\n

\n Welcome on my awesome homepage.\n {% endblock %}\n\nThe ``{% extends %}`` tag is the key here. It tells the template engine that\nthis template \"extends\" another template. When the template system evaluates\nthis template, first it locates the parent. The extends tag must be the\nfirst tag in the template. To render the contents of a block defined in\nthe parent template, use ``{{ super() }}``.\n"},{"id":265,"name":"examples/javascript","nodeType":"Package"},{"id":266,"name":"LICENSE.rst","nodeType":"TextFile","path":"examples/javascript","text":"Copyright 2010 Pallets\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\nTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"col":0,"comment":"null","endLoc":10,"header":"@pytest.fixture(name=\"app\")\ndef fixture_app()","id":267,"name":"fixture_app","nodeType":"Function","startLoc":6,"text":"@pytest.fixture(name=\"app\")\ndef fixture_app():\n app.testing = True\n yield app\n app.testing = False"},{"className":"TestGreenletContextCopying","col":0,"comment":"null","endLoc":202,"id":268,"nodeType":"Class","startLoc":148,"text":"@pytest.mark.skipif(greenlet is None, reason=\"greenlet not installed\")\nclass TestGreenletContextCopying:\n def test_greenlet_context_copying(self, app, client):\n greenlets = []\n\n @app.route(\"/\")\n def index():\n flask.session[\"fizz\"] = \"buzz\"\n reqctx = request_ctx.copy()\n\n def g():\n assert not flask.request\n assert not flask.current_app\n with reqctx:\n assert flask.request\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session.get(\"fizz\") == \"buzz\"\n assert not flask.request\n return 42\n\n greenlets.append(greenlet(g))\n return \"Hello World!\"\n\n rv = client.get(\"/?foo=bar\")\n assert rv.data == b\"Hello World!\"\n\n result = greenlets[0].run()\n assert result == 42\n\n def test_greenlet_context_copying_api(self, app, client):\n greenlets = []\n\n @app.route(\"/\")\n def index():\n flask.session[\"fizz\"] = \"buzz\"\n\n @flask.copy_current_request_context\n def g():\n assert flask.request\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session.get(\"fizz\") == \"buzz\"\n return 42\n\n greenlets.append(greenlet(g))\n return \"Hello World!\"\n\n rv = client.get(\"/?foo=bar\")\n assert rv.data == b\"Hello World!\"\n\n result = greenlets[0].run()\n assert result == 42"},{"col":4,"comment":"null","endLoc":177,"header":"def test_greenlet_context_copying(self, app, client)","id":269,"name":"test_greenlet_context_copying","nodeType":"Function","startLoc":150,"text":"def test_greenlet_context_copying(self, app, client):\n greenlets = []\n\n @app.route(\"/\")\n def index():\n flask.session[\"fizz\"] = \"buzz\"\n reqctx = request_ctx.copy()\n\n def g():\n assert not flask.request\n assert not flask.current_app\n with reqctx:\n assert flask.request\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session.get(\"fizz\") == \"buzz\"\n assert not flask.request\n return 42\n\n greenlets.append(greenlet(g))\n return \"Hello World!\"\n\n rv = client.get(\"/?foo=bar\")\n assert rv.data == b\"Hello World!\"\n\n result = greenlets[0].run()\n assert result == 42"},{"col":0,"comment":"Clear existing data and create new tables.","endLoc":37,"header":"def init_db()","id":270,"name":"init_db","nodeType":"Function","startLoc":32,"text":"def init_db():\n \"\"\"Clear existing data and create new tables.\"\"\"\n db = get_db()\n\n with current_app.open_resource(\"schema.sql\") as f:\n db.executescript(f.read().decode(\"utf8\"))"},{"col":0,"comment":"null","endLoc":15,"header":"@pytest.fixture\ndef client(app)","id":271,"name":"client","nodeType":"Function","startLoc":13,"text":"@pytest.fixture\ndef client(app):\n return app.test_client()"},{"attributeType":"(...) -> Any","col":4,"comment":"null","endLoc":70,"id":272,"name":"write","nodeType":"Attribute","startLoc":70,"text":"write"},{"col":4,"comment":"null","endLoc":138,"header":"def __iter__(self) -> Iterator[str]","id":273,"name":"__iter__","nodeType":"Function","startLoc":138,"text":"def __iter__(self) -> Iterator[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":139,"header":"def __next__(self) -> str","id":274,"name":"__next__","nodeType":"Function","startLoc":139,"text":"def __next__(self) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":140,"header":"def detach(self) -> BinaryIO","id":275,"name":"detach","nodeType":"Function","startLoc":140,"text":"def detach(self) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":141,"header":"def write(self, __s: str) -> int","id":276,"name":"write","nodeType":"Function","startLoc":141,"text":"def write(self, __s: str) -> int: ..."},{"col":4,"comment":"null","endLoc":142,"header":"def writelines(self, __lines: Iterable[str]) -> None","id":277,"name":"writelines","nodeType":"Function","startLoc":142,"text":"def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":143,"header":"def readline(self, __size: int = ...) -> str","id":278,"name":"readline","nodeType":"Function","startLoc":143,"text":"def readline(self, __size: int = ...) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":144,"header":"def readlines(self, __hint: int = -1) -> list[str]","id":279,"name":"readlines","nodeType":"Function","startLoc":144,"text":"def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":145,"header":"def read(self, __size: int | None = ...) -> str","id":280,"name":"read","nodeType":"Function","startLoc":145,"text":"def read(self, __size: int | None = ...) -> str: ..."},{"attributeType":"str","col":4,"comment":"null","endLoc":135,"id":281,"name":"encoding","nodeType":"Attribute","startLoc":135,"text":"encoding"},{"className":"int","col":0,"comment":"null","endLoc":327,"id":282,"nodeType":"Class","startLoc":222,"text":"class int:\n @overload\n def __new__(cls, __x: ConvertibleToInt = ...) -> Self: ...\n @overload\n def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ...\n if sys.version_info >= (3, 8):\n def as_integer_ratio(self) -> tuple[int, Literal[1]]: ...\n\n @property\n def real(self) -> int: ...\n @property\n def imag(self) -> Literal[0]: ...\n @property\n def numerator(self) -> int: ...\n @property\n def denominator(self) -> Literal[1]: ...\n def conjugate(self) -> int: ...\n def bit_length(self) -> int: ...\n if sys.version_info >= (3, 10):\n def bit_count(self) -> int: ...\n\n if sys.version_info >= (3, 11):\n def to_bytes(\n self, length: SupportsIndex = 1, byteorder: Literal[\"little\", \"big\"] = \"big\", *, signed: bool = False\n ) -> bytes: ...\n @classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"] = \"big\",\n *,\n signed: bool = False,\n ) -> Self: ...\n else:\n def to_bytes(self, length: SupportsIndex, byteorder: Literal[\"little\", \"big\"], *, signed: bool = False) -> bytes: ...\n @classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"],\n *,\n signed: bool = False,\n ) -> Self: ...\n\n if sys.version_info >= (3, 12):\n def is_integer(self) -> Literal[True]: ...\n\n def __add__(self, __value: int) -> int: ...\n def __sub__(self, __value: int) -> int: ...\n def __mul__(self, __value: int) -> int: ...\n def __floordiv__(self, __value: int) -> int: ...\n def __truediv__(self, __value: int) -> float: ...\n def __mod__(self, __value: int) -> int: ...\n def __divmod__(self, __value: int) -> tuple[int, int]: ...\n def __radd__(self, __value: int) -> int: ...\n def __rsub__(self, __value: int) -> int: ...\n def __rmul__(self, __value: int) -> int: ...\n def __rfloordiv__(self, __value: int) -> int: ...\n def __rtruediv__(self, __value: int) -> float: ...\n def __rmod__(self, __value: int) -> int: ...\n def __rdivmod__(self, __value: int) -> tuple[int, int]: ...\n @overload\n def __pow__(self, __x: Literal[0]) -> Literal[1]: ...\n @overload\n def __pow__(self, __value: Literal[0], __mod: None) -> Literal[1]: ...\n @overload\n def __pow__(self, __value: _PositiveInteger, __mod: None = None) -> int: ...\n @overload\n def __pow__(self, __value: _NegativeInteger, __mod: None = None) -> float: ...\n # positive x -> int; negative x -> float\n # return type must be Any as `int | float` causes too many false-positive errors\n @overload\n def __pow__(self, __value: int, __mod: None = None) -> Any: ...\n @overload\n def __pow__(self, __value: int, __mod: int) -> int: ...\n def __rpow__(self, __value: int, __mod: int | None = None) -> Any: ...\n def __and__(self, __value: int) -> int: ...\n def __or__(self, __value: int) -> int: ...\n def __xor__(self, __value: int) -> int: ...\n def __lshift__(self, __value: int) -> int: ...\n def __rshift__(self, __value: int) -> int: ...\n def __rand__(self, __value: int) -> int: ...\n def __ror__(self, __value: int) -> int: ...\n def __rxor__(self, __value: int) -> int: ...\n def __rlshift__(self, __value: int) -> int: ...\n def __rrshift__(self, __value: int) -> int: ...\n def __neg__(self) -> int: ...\n def __pos__(self) -> int: ...\n def __invert__(self) -> int: ...\n def __trunc__(self) -> int: ...\n def __ceil__(self) -> int: ...\n def __floor__(self) -> int: ...\n def __round__(self, __ndigits: SupportsIndex = ...) -> int: ...\n def __getnewargs__(self) -> tuple[int]: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __lt__(self, __value: int) -> bool: ...\n def __le__(self, __value: int) -> bool: ...\n def __gt__(self, __value: int) -> bool: ...\n def __ge__(self, __value: int) -> bool: ...\n def __float__(self) -> float: ...\n def __int__(self) -> int: ...\n def __abs__(self) -> int: ...\n def __hash__(self) -> int: ...\n def __bool__(self) -> bool: ...\n def __index__(self) -> int: ..."},{"className":"int","col":0,"comment":"null","endLoc":327,"id":283,"nodeType":"Class","startLoc":222,"text":"class int:\n @overload\n def __new__(cls, __x: ConvertibleToInt = ...) -> Self: ...\n @overload\n def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ...\n if sys.version_info >= (3, 8):\n def as_integer_ratio(self) -> tuple[int, Literal[1]]: ...\n\n @property\n def real(self) -> int: ...\n @property\n def imag(self) -> Literal[0]: ...\n @property\n def numerator(self) -> int: ...\n @property\n def denominator(self) -> Literal[1]: ...\n def conjugate(self) -> int: ...\n def bit_length(self) -> int: ...\n if sys.version_info >= (3, 10):\n def bit_count(self) -> int: ...\n\n if sys.version_info >= (3, 11):\n def to_bytes(\n self, length: SupportsIndex = 1, byteorder: Literal[\"little\", \"big\"] = \"big\", *, signed: bool = False\n ) -> bytes: ...\n @classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"] = \"big\",\n *,\n signed: bool = False,\n ) -> Self: ...\n else:\n def to_bytes(self, length: SupportsIndex, byteorder: Literal[\"little\", \"big\"], *, signed: bool = False) -> bytes: ...\n @classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"],\n *,\n signed: bool = False,\n ) -> Self: ...\n\n if sys.version_info >= (3, 12):\n def is_integer(self) -> Literal[True]: ...\n\n def __add__(self, __value: int) -> int: ...\n def __sub__(self, __value: int) -> int: ...\n def __mul__(self, __value: int) -> int: ...\n def __floordiv__(self, __value: int) -> int: ...\n def __truediv__(self, __value: int) -> float: ...\n def __mod__(self, __value: int) -> int: ...\n def __divmod__(self, __value: int) -> tuple[int, int]: ...\n def __radd__(self, __value: int) -> int: ...\n def __rsub__(self, __value: int) -> int: ...\n def __rmul__(self, __value: int) -> int: ...\n def __rfloordiv__(self, __value: int) -> int: ...\n def __rtruediv__(self, __value: int) -> float: ...\n def __rmod__(self, __value: int) -> int: ...\n def __rdivmod__(self, __value: int) -> tuple[int, int]: ...\n @overload\n def __pow__(self, __x: Literal[0]) -> Literal[1]: ...\n @overload\n def __pow__(self, __value: Literal[0], __mod: None) -> Literal[1]: ...\n @overload\n def __pow__(self, __value: _PositiveInteger, __mod: None = None) -> int: ...\n @overload\n def __pow__(self, __value: _NegativeInteger, __mod: None = None) -> float: ...\n # positive x -> int; negative x -> float\n # return type must be Any as `int | float` causes too many false-positive errors\n @overload\n def __pow__(self, __value: int, __mod: None = None) -> Any: ...\n @overload\n def __pow__(self, __value: int, __mod: int) -> int: ...\n def __rpow__(self, __value: int, __mod: int | None = None) -> Any: ...\n def __and__(self, __value: int) -> int: ...\n def __or__(self, __value: int) -> int: ...\n def __xor__(self, __value: int) -> int: ...\n def __lshift__(self, __value: int) -> int: ...\n def __rshift__(self, __value: int) -> int: ...\n def __rand__(self, __value: int) -> int: ...\n def __ror__(self, __value: int) -> int: ...\n def __rxor__(self, __value: int) -> int: ...\n def __rlshift__(self, __value: int) -> int: ...\n def __rrshift__(self, __value: int) -> int: ...\n def __neg__(self) -> int: ...\n def __pos__(self) -> int: ...\n def __invert__(self) -> int: ...\n def __trunc__(self) -> int: ...\n def __ceil__(self) -> int: ...\n def __floor__(self) -> int: ...\n def __round__(self, __ndigits: SupportsIndex = ...) -> int: ...\n def __getnewargs__(self) -> tuple[int]: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __lt__(self, __value: int) -> bool: ...\n def __le__(self, __value: int) -> bool: ...\n def __gt__(self, __value: int) -> bool: ...\n def __ge__(self, __value: int) -> bool: ...\n def __float__(self) -> float: ...\n def __int__(self) -> int: ...\n def __abs__(self) -> int: ...\n def __hash__(self) -> int: ...\n def __bool__(self) -> bool: ...\n def __index__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":30,"header":"def __getattr__(self, name)","id":285,"name":"__getattr__","nodeType":"Function","startLoc":29,"text":"def __getattr__(self, name):\n return getattr(self._io, name)"},{"id":286,"name":"dev.txt","nodeType":"TextFile","path":"requirements","text":"# SHA1:54b5b77ec8c7a0064ffa93b2fd16cb0130ba177c\n#\n# This file is autogenerated by pip-compile-multi\n# To update, run:\n#\n# pip-compile-multi\n#\n-r docs.txt\n-r tests.txt\n-r typing.txt\nbuild==0.10.0\n # via pip-tools\ncachetools==5.3.0\n # via tox\ncfgv==3.3.1\n # via pre-commit\nchardet==5.1.0\n # via tox\nclick==8.1.3\n # via\n # pip-compile-multi\n # pip-tools\ncolorama==0.4.6\n # via tox\ndistlib==0.3.6\n # via virtualenv\nfilelock==3.11.0\n # via\n # tox\n # virtualenv\nidentify==2.5.22\n # via pre-commit\nnodeenv==1.7.0\n # via pre-commit\npip-compile-multi==2.6.2\n # via -r requirements/dev.in\npip-tools==6.13.0\n # via pip-compile-multi\nplatformdirs==3.2.0\n # via\n # tox\n # virtualenv\npre-commit==3.2.2\n # via -r requirements/dev.in\npyproject-api==1.5.1\n # via tox\npyproject-hooks==1.0.0\n # via build\npyyaml==6.0\n # via pre-commit\ntoposort==1.10\n # via pip-compile-multi\ntox==4.4.11\n # via -r requirements/dev.in\nvirtualenv==20.21.0\n # via\n # pre-commit\n # tox\nwheel==0.40.0\n # via pip-tools\n\n# The following packages are considered to be unsafe in a requirements file:\n# pip\n# setuptools\n"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":136,"id":289,"name":"errors","nodeType":"Attribute","startLoc":136,"text":"errors"},{"attributeType":"str | (str, ...) | None","col":4,"comment":"null","endLoc":137,"id":291,"name":"newlines","nodeType":"Attribute","startLoc":137,"text":"newlines"},{"id":292,"name":"sqlite3.rst","nodeType":"TextFile","path":"docs/patterns","text":"Using SQLite 3 with Flask\n=========================\n\nIn Flask you can easily implement the opening of database connections on\ndemand and closing them when the context dies (usually at the end of the\nrequest).\n\nHere is a simple example of how you can use SQLite 3 with Flask::\n\n import sqlite3\n from flask import g\n\n DATABASE = '/path/to/database.db'\n\n def get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n return db\n\n @app.teardown_appcontext\n def close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n\nNow, to use the database, the application must either have an active\napplication context (which is always true if there is a request in flight)\nor create an application context itself. At that point the ``get_db``\nfunction can be used to get the current database connection. Whenever the\ncontext is destroyed the database connection will be terminated.\n\nExample::\n\n @app.route('/')\n def index():\n cur = get_db().cursor()\n ...\n\n\n.. note::\n\n Please keep in mind that the teardown request and appcontext functions\n are always executed, even if a before-request handler failed or was\n never executed. Because of this we have to make sure here that the\n database is there before we close it.\n\nConnect on Demand\n-----------------\n\nThe upside of this approach (connecting on first use) is that this will\nonly open the connection if truly necessary. If you want to use this\ncode outside a request context you can use it in a Python shell by opening\nthe application context by hand::\n\n with app.app_context():\n # now you can use get_db()\n\n\nEasy Querying\n-------------\n\nNow in each request handling function you can access `get_db()` to get the\ncurrent open database connection. To simplify working with SQLite, a\nrow factory function is useful. It is executed for every result returned\nfrom the database to convert the result. For instance, in order to get\ndictionaries instead of tuples, this could be inserted into the ``get_db``\nfunction we created above::\n\n def make_dicts(cursor, row):\n return dict((cursor.description[idx][0], value)\n for idx, value in enumerate(row))\n\n db.row_factory = make_dicts\n\nThis will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::\n\n db.row_factory = sqlite3.Row\n\nThis would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::\n\n >>> # You can get values based on the row's name\n >>> r['FirstName']\n John\n >>> # Or, you can get them based on index\n >>> r[1]\n John\n # Row objects are also iterable:\n >>> for value in r:\n ... print(value)\n 1\n John\n Doe\n M\n\nAdditionally, it is a good idea to provide a query function that combines\ngetting the cursor, executing and fetching the results::\n\n def query_db(query, args=(), one=False):\n cur = get_db().execute(query, args)\n rv = cur.fetchall()\n cur.close()\n return (rv[0] if rv else None) if one else rv\n\nThis handy little function, in combination with a row factory, makes\nworking with the database much more pleasant than it is by just using the\nraw cursor and connection objects.\n\nHere is how you can use it::\n\n for user in query_db('select * from users'):\n print(user['username'], 'has the id', user['user_id'])\n\nOr if you just want a single result::\n\n user = query_db('select * from users where username = ?',\n [the_username], one=True)\n if user is None:\n print('No such user')\n else:\n print(the_username, 'has the id', user['user_id'])\n\nTo pass variable parts to the SQL statement, use a question mark in the\nstatement and pass in the arguments as a list. Never directly add them to\nthe SQL statement with string formatting because this makes it possible\nto attack the application using `SQL Injections\n`_.\n\nInitial Schemas\n---------------\n\nRelational databases need schemas, so applications often ship a\n`schema.sql` file that creates the database. It's a good idea to provide\na function that creates the database based on that schema. This function\ncan do that for you::\n\n def init_db():\n with app.app_context():\n db = get_db()\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\nYou can then create such a database from the Python shell:\n\n>>> from yourapplication import init_db\n>>> init_db()\n"},{"fileName":"test_templating.py","filePath":"tests","id":293,"nodeType":"File","text":"import logging\n\nimport pytest\nimport werkzeug.serving\nfrom jinja2 import TemplateNotFound\nfrom markupsafe import Markup\n\nimport flask\n\n\ndef test_context_processing(app, client):\n @app.context_processor\n def context_processor():\n return {\"injected_value\": 42}\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"context_template.html\", value=23)\n\n rv = client.get(\"/\")\n assert rv.data == b\"

23|42\"\n\n\ndef test_original_win(app, client):\n @app.route(\"/\")\n def index():\n return flask.render_template_string(\"{{ config }}\", config=42)\n\n rv = client.get(\"/\")\n assert rv.data == b\"42\"\n\n\ndef test_simple_stream(app, client):\n @app.route(\"/\")\n def index():\n return flask.stream_template_string(\"{{ config }}\", config=42)\n\n rv = client.get(\"/\")\n assert rv.data == b\"42\"\n\n\ndef test_request_less_rendering(app, app_ctx):\n app.config[\"WORLD_NAME\"] = \"Special World\"\n\n @app.context_processor\n def context_processor():\n return dict(foo=42)\n\n rv = flask.render_template_string(\"Hello {{ config.WORLD_NAME }} {{ foo }}\")\n assert rv == \"Hello Special World 42\"\n\n\ndef test_standard_context(app, client):\n @app.route(\"/\")\n def index():\n flask.g.foo = 23\n flask.session[\"test\"] = \"aha\"\n return flask.render_template_string(\n \"\"\"\n {{ request.args.foo }}\n {{ g.foo }}\n {{ config.DEBUG }}\n {{ session.test }}\n \"\"\"\n )\n\n rv = client.get(\"/?foo=42\")\n assert rv.data.split() == [b\"42\", b\"23\", b\"False\", b\"aha\"]\n\n\ndef test_escaping(app, client):\n text = \"

Hello World!\"\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\n \"escaping_template.html\", text=text, html=Markup(text)\n )\n\n lines = client.get(\"/\").data.splitlines()\n assert lines == [\n b\"<p>Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"<p>Hello World!\",\n b\"

Hello World!\",\n ]\n\n\ndef test_no_escaping(app, client):\n text = \"

Hello World!\"\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\n \"non_escaping_template.txt\", text=text, html=Markup(text)\n )\n\n lines = client.get(\"/\").data.splitlines()\n assert lines == [\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"<p>Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n b\"

Hello World!\",\n ]\n\n\ndef test_escaping_without_template_filename(app, client, req_ctx):\n assert flask.render_template_string(\"{{ foo }}\", foo=\"\") == \"<test>\"\n assert flask.render_template(\"mail.txt\", foo=\"\") == \" Mail\"\n\n\ndef test_macros(app, req_ctx):\n macro = flask.get_template_attribute(\"_macro.html\", \"hello\")\n assert macro(\"World\") == \"Hello World!\"\n\n\ndef test_template_filter(app):\n @app.template_filter()\n def my_reverse(s):\n return s[::-1]\n\n assert \"my_reverse\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse\"] == my_reverse\n assert app.jinja_env.filters[\"my_reverse\"](\"abcd\") == \"dcba\"\n\n\ndef test_add_template_filter(app):\n def my_reverse(s):\n return s[::-1]\n\n app.add_template_filter(my_reverse)\n assert \"my_reverse\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"my_reverse\"] == my_reverse\n assert app.jinja_env.filters[\"my_reverse\"](\"abcd\") == \"dcba\"\n\n\ndef test_template_filter_with_name(app):\n @app.template_filter(\"strrev\")\n def my_reverse(s):\n return s[::-1]\n\n assert \"strrev\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"strrev\"] == my_reverse\n assert app.jinja_env.filters[\"strrev\"](\"abcd\") == \"dcba\"\n\n\ndef test_add_template_filter_with_name(app):\n def my_reverse(s):\n return s[::-1]\n\n app.add_template_filter(my_reverse, \"strrev\")\n assert \"strrev\" in app.jinja_env.filters.keys()\n assert app.jinja_env.filters[\"strrev\"] == my_reverse\n assert app.jinja_env.filters[\"strrev\"](\"abcd\") == \"dcba\"\n\n\ndef test_template_filter_with_template(app, client):\n @app.template_filter()\n def super_reverse(s):\n return s[::-1]\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\"\n\n\ndef test_add_template_filter_with_template(app, client):\n def super_reverse(s):\n return s[::-1]\n\n app.add_template_filter(super_reverse)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\"\n\n\ndef test_template_filter_with_name_and_template(app, client):\n @app.template_filter(\"super_reverse\")\n def my_reverse(s):\n return s[::-1]\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\"\n\n\ndef test_add_template_filter_with_name_and_template(app, client):\n def my_reverse(s):\n return s[::-1]\n\n app.add_template_filter(my_reverse, \"super_reverse\")\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_filter.html\", value=\"abcd\")\n\n rv = client.get(\"/\")\n assert rv.data == b\"dcba\"\n\n\ndef test_template_test(app):\n @app.template_test()\n def boolean(value):\n return isinstance(value, bool)\n\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == boolean\n assert app.jinja_env.tests[\"boolean\"](False)\n\n\ndef test_add_template_test(app):\n def boolean(value):\n return isinstance(value, bool)\n\n app.add_template_test(boolean)\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == boolean\n assert app.jinja_env.tests[\"boolean\"](False)\n\n\ndef test_template_test_with_name(app):\n @app.template_test(\"boolean\")\n def is_boolean(value):\n return isinstance(value, bool)\n\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == is_boolean\n assert app.jinja_env.tests[\"boolean\"](False)\n\n\ndef test_add_template_test_with_name(app):\n def is_boolean(value):\n return isinstance(value, bool)\n\n app.add_template_test(is_boolean, \"boolean\")\n assert \"boolean\" in app.jinja_env.tests.keys()\n assert app.jinja_env.tests[\"boolean\"] == is_boolean\n assert app.jinja_env.tests[\"boolean\"](False)\n\n\ndef test_template_test_with_template(app, client):\n @app.template_test()\n def boolean(value):\n return isinstance(value, bool)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_test.html\", value=False)\n\n rv = client.get(\"/\")\n assert b\"Success!\" in rv.data\n\n\ndef test_add_template_test_with_template(app, client):\n def boolean(value):\n return isinstance(value, bool)\n\n app.add_template_test(boolean)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_test.html\", value=False)\n\n rv = client.get(\"/\")\n assert b\"Success!\" in rv.data\n\n\ndef test_template_test_with_name_and_template(app, client):\n @app.template_test(\"boolean\")\n def is_boolean(value):\n return isinstance(value, bool)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_test.html\", value=False)\n\n rv = client.get(\"/\")\n assert b\"Success!\" in rv.data\n\n\ndef test_add_template_test_with_name_and_template(app, client):\n def is_boolean(value):\n return isinstance(value, bool)\n\n app.add_template_test(is_boolean, \"boolean\")\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"template_test.html\", value=False)\n\n rv = client.get(\"/\")\n assert b\"Success!\" in rv.data\n\n\ndef test_add_template_global(app, app_ctx):\n @app.template_global()\n def get_stuff():\n return 42\n\n assert \"get_stuff\" in app.jinja_env.globals.keys()\n assert app.jinja_env.globals[\"get_stuff\"] == get_stuff\n assert app.jinja_env.globals[\"get_stuff\"](), 42\n\n rv = flask.render_template_string(\"{{ get_stuff() }}\")\n assert rv == \"42\"\n\n\ndef test_custom_template_loader(client):\n class MyFlask(flask.Flask):\n def create_global_jinja_loader(self):\n from jinja2 import DictLoader\n\n return DictLoader({\"index.html\": \"Hello Custom World!\"})\n\n app = MyFlask(__name__)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"index.html\")\n\n c = app.test_client()\n rv = c.get(\"/\")\n assert rv.data == b\"Hello Custom World!\"\n\n\ndef test_iterable_loader(app, client):\n @app.context_processor\n def context_processor():\n return {\"whiskey\": \"Jameson\"}\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\n [\n \"no_template.xml\", # should skip this one\n \"simple_template.html\", # should render this\n \"context_template.html\",\n ],\n value=23,\n )\n\n rv = client.get(\"/\")\n assert rv.data == b\"

Jameson

\"\n\n\ndef test_templates_auto_reload(app):\n # debug is False, config option is None\n assert app.debug is False\n assert app.config[\"TEMPLATES_AUTO_RELOAD\"] is None\n assert app.jinja_env.auto_reload is False\n # debug is False, config option is False\n app = flask.Flask(__name__)\n app.config[\"TEMPLATES_AUTO_RELOAD\"] = False\n assert app.debug is False\n assert app.jinja_env.auto_reload is False\n # debug is False, config option is True\n app = flask.Flask(__name__)\n app.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n assert app.debug is False\n assert app.jinja_env.auto_reload is True\n # debug is True, config option is None\n app = flask.Flask(__name__)\n app.config[\"DEBUG\"] = True\n assert app.config[\"TEMPLATES_AUTO_RELOAD\"] is None\n assert app.jinja_env.auto_reload is True\n # debug is True, config option is False\n app = flask.Flask(__name__)\n app.config[\"DEBUG\"] = True\n app.config[\"TEMPLATES_AUTO_RELOAD\"] = False\n assert app.jinja_env.auto_reload is False\n # debug is True, config option is True\n app = flask.Flask(__name__)\n app.config[\"DEBUG\"] = True\n app.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n assert app.jinja_env.auto_reload is True\n\n\ndef test_templates_auto_reload_debug_run(app, monkeypatch):\n def run_simple_mock(*args, **kwargs):\n pass\n\n monkeypatch.setattr(werkzeug.serving, \"run_simple\", run_simple_mock)\n\n app.run()\n assert not app.jinja_env.auto_reload\n\n app.run(debug=True)\n assert app.jinja_env.auto_reload\n\n\ndef test_template_loader_debugging(test_apps, monkeypatch):\n from blueprintapp import app\n\n called = []\n\n class _TestHandler(logging.Handler):\n def handle(self, record):\n called.append(True)\n text = str(record.msg)\n assert \"1: trying loader of application 'blueprintapp'\" in text\n assert (\n \"2: trying loader of blueprint 'admin' (blueprintapp.apps.admin)\"\n ) in text\n assert (\n \"trying loader of blueprint 'frontend' (blueprintapp.apps.frontend)\"\n ) in text\n assert \"Error: the template could not be found\" in text\n assert (\n \"looked up from an endpoint that belongs to the blueprint 'frontend'\"\n ) in text\n assert \"See https://flask.palletsprojects.com/blueprints/#templates\" in text\n\n with app.test_client() as c:\n monkeypatch.setitem(app.config, \"EXPLAIN_TEMPLATE_LOADING\", True)\n monkeypatch.setattr(\n logging.getLogger(\"blueprintapp\"), \"handlers\", [_TestHandler()]\n )\n\n with pytest.raises(TemplateNotFound) as excinfo:\n c.get(\"/missing\")\n\n assert \"missing_template.html\" in str(excinfo.value)\n\n assert len(called) == 1\n\n\ndef test_custom_jinja_env():\n class CustomEnvironment(flask.templating.Environment):\n pass\n\n class CustomFlask(flask.Flask):\n jinja_environment = CustomEnvironment\n\n app = CustomFlask(__name__)\n assert isinstance(app.jinja_env, CustomEnvironment)\n"},{"col":4,"comment":"null","endLoc":70,"header":"@overload\n def lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]","id":294,"name":"lru_cache","nodeType":"Function","startLoc":69,"text":"@overload\n def lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]: ..."},{"col":4,"comment":"null","endLoc":73,"header":"def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]","id":295,"name":"lru_cache","nodeType":"Function","startLoc":73,"text":"def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ..."},{"className":"TextIO","col":0,"comment":"null","endLoc":770,"id":297,"nodeType":"Class","startLoc":757,"text":"class TextIO(IO[str]):\n # See comment regarding the @properties in the `IO` class\n @property\n def buffer(self) -> BinaryIO: ...\n @property\n def encoding(self) -> str: ...\n @property\n def errors(self) -> str | None: ...\n @property\n def line_buffering(self) -> int: ... # int on PyPy, bool on CPython\n @property\n def newlines(self) -> Any: ... # None, str or tuple\n @abstractmethod\n def __enter__(self) -> TextIO: ..."},{"id":298,"name":"docs/tutorial","nodeType":"Package"},{"id":299,"name":"index.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Tutorial\n========\n\n.. toctree::\n :caption: Contents:\n :maxdepth: 1\n\n layout\n factory\n database\n views\n templates\n static\n blog\n install\n tests\n deploy\n next\n\nThis tutorial will walk you through creating a basic blog application\ncalled Flaskr. Users will be able to register, log in, create posts,\nand edit or delete their own posts. You will be able to package and\ninstall the application on other computers.\n\n.. image:: flaskr_index.png\n :align: center\n :class: screenshot\n :alt: screenshot of index page\n\nIt's assumed that you're already familiar with Python. The `official\ntutorial`_ in the Python docs is a great way to learn or review first.\n\n.. _official tutorial: https://docs.python.org/3/tutorial/\n\nWhile it's designed to give a good starting point, the tutorial doesn't\ncover all of Flask's features. Check out the :doc:`/quickstart` for an\noverview of what Flask can do, then dive into the docs to find out more.\nThe tutorial only uses what's provided by Flask and Python. In another\nproject, you might decide to use :doc:`/extensions` or other libraries\nto make some tasks simpler.\n\n.. image:: flaskr_login.png\n :align: center\n :class: screenshot\n :alt: screenshot of login page\n\nFlask is flexible. It doesn't require you to use any particular project\nor code layout. However, when first starting, it's helpful to use a more\nstructured approach. This means that the tutorial will require a bit of\nboilerplate up front, but it's done to avoid many common pitfalls that\nnew developers encounter, and it creates a project that's easy to expand\non. Once you become more comfortable with Flask, you can step out of\nthis structure and take full advantage of Flask's flexibility.\n\n.. image:: flaskr_edit.png\n :align: center\n :class: screenshot\n :alt: screenshot of edit page\n\n:gh:`The tutorial project is available as an example in the Flask\nrepository `, if you want to compare your project\nwith the final product as you follow the tutorial.\n\nContinue to :doc:`layout`.\n"},{"id":301,"name":"install.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Make the Project Installable\n============================\n\nMaking your project installable means that you can build a *wheel* file and install that\nin another environment, just like you installed Flask in your project's environment.\nThis makes deploying your project the same as installing any other library, so you're\nusing all the standard Python tools to manage everything.\n\nInstalling also comes with other benefits that might not be obvious from\nthe tutorial or as a new Python user, including:\n\n* Currently, Python and Flask understand how to use the ``flaskr``\n package only because you're running from your project's directory.\n Installing means you can import it no matter where you run from.\n\n* You can manage your project's dependencies just like other packages\n do, so ``pip install yourproject.whl`` installs them.\n\n* Test tools can isolate your test environment from your development\n environment.\n\n.. note::\n This is being introduced late in the tutorial, but in your future\n projects you should always start with this.\n\n\nDescribe the Project\n--------------------\n\nThe ``pyproject.toml`` file describes your project and how to build it.\n\n.. code-block:: toml\n :caption: ``pyproject.toml``\n\n [project]\n name = \"flaskr\"\n version = \"1.0.0\"\n dependencies = [\n \"flask\",\n ]\n\n [build-system]\n requires = [\"setuptools\"]\n build-backend = \"setuptools.build_meta\"\n\n\nThe setuptools build backend needs another file named ``MANIFEST.in`` to tell it about\nnon-Python files to include.\n\n.. code-block:: none\n :caption: ``MANIFEST.in``\n\n include flaskr/schema.sql\n graft flaskr/static\n graft flaskr/templates\n global-exclude *.pyc\n\nThis tells the build to copy everything in the ``static`` and ``templates`` directories,\nand the ``schema.sql`` file, but to exclude all bytecode files.\n\nSee the official `Packaging tutorial `_ and\n`detailed guide `_ for more explanation of the files\nand options used.\n\n.. _packaging tutorial: https://packaging.python.org/tutorials/packaging-projects/\n.. _packaging guide: https://packaging.python.org/guides/distributing-packages-using-setuptools/\n\n\nInstall the Project\n-------------------\n\nUse ``pip`` to install your project in the virtual environment.\n\n.. code-block:: none\n\n $ pip install -e .\n\nThis tells pip to find ``pyproject.toml`` in the current directory and install the\nproject in *editable* or *development* mode. Editable mode means that as you make\nchanges to your local code, you'll only need to re-install if you change the metadata\nabout the project, such as its dependencies.\n\nYou can observe that the project is now installed with ``pip list``.\n\n.. code-block:: none\n\n $ pip list\n\n Package Version Location\n -------------- --------- ----------------------------------\n click 6.7\n Flask 1.0\n flaskr 1.0.0 /home/user/Projects/flask-tutorial\n itsdangerous 0.24\n Jinja2 2.10\n MarkupSafe 1.0\n pip 9.0.3\n setuptools 39.0.1\n Werkzeug 0.14.1\n wheel 0.30.0\n\nNothing changes from how you've been running your project so far.\n``--app`` is still set to ``flaskr`` and ``flask run`` still runs\nthe application, but you can call it from anywhere, not just the\n``flask-tutorial`` directory.\n\nContinue to :doc:`tests`.\n"},{"id":302,"name":"src/flask/json","nodeType":"Package"},{"fileName":"provider.py","filePath":"src/flask/json","id":303,"nodeType":"File","text":"from __future__ import annotations\n\nimport dataclasses\nimport decimal\nimport json\nimport typing as t\nimport uuid\nimport weakref\nfrom datetime import date\n\nfrom werkzeug.http import http_date\n\nif t.TYPE_CHECKING: # pragma: no cover\n from ..app import Flask\n from ..wrappers import Response\n\n\nclass JSONProvider:\n \"\"\"A standard set of JSON operations for an application. Subclasses\n of this can be used to customize JSON behavior or use different\n JSON libraries.\n\n To implement a provider for a specific library, subclass this base\n class and implement at least :meth:`dumps` and :meth:`loads`. All\n other methods have default implementations.\n\n To use a different provider, either subclass ``Flask`` and set\n :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n :attr:`app.json ` to an instance of the class.\n\n :param app: An application instance. This will be stored as a\n :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n .. versionadded:: 2.2\n \"\"\"\n\n def __init__(self, app: Flask) -> None:\n self._app = weakref.proxy(app)\n\n def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n :param obj: The data to serialize.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError\n\n def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write to a file.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n fp.write(self.dumps(obj, **kwargs))\n\n def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError\n\n def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON read from a file.\n\n :param fp: A file opened for reading text or UTF-8 bytes.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n return self.loads(fp.read(), **kwargs)\n\n def _prepare_response_obj(\n self, args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]\n ) -> t.Any:\n if args and kwargs:\n raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n if not args and not kwargs:\n return None\n\n if len(args) == 1:\n return args[0]\n\n return args or kwargs\n\n def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with the ``application/json``\n mimetype.\n\n The :func:`~flask.json.jsonify` function calls this method for\n the current application.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n \"\"\"\n obj = self._prepare_response_obj(args, kwargs)\n return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n\n\ndef _default(o: t.Any) -> t.Any:\n if isinstance(o, date):\n return http_date(o)\n\n if isinstance(o, (decimal.Decimal, uuid.UUID)):\n return str(o)\n\n if dataclasses and dataclasses.is_dataclass(o):\n return dataclasses.asdict(o)\n\n if hasattr(o, \"__html__\"):\n return str(o.__html__())\n\n raise TypeError(f\"Object of type {type(o).__name__} is not JSON serializable\")\n\n\nclass DefaultJSONProvider(JSONProvider):\n \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n library. Serializes the following additional data types:\n\n - :class:`datetime.datetime` and :class:`datetime.date` are\n serialized to :rfc:`822` strings. This is the same as the HTTP\n date format.\n - :class:`uuid.UUID` is serialized to a string.\n - :class:`dataclasses.dataclass` is passed to\n :func:`dataclasses.asdict`.\n - :class:`~markupsafe.Markup` (or any object with a ``__html__``\n method) will call the ``__html__`` method to get a string.\n \"\"\"\n\n default: t.Callable[[t.Any], t.Any] = staticmethod(\n _default\n ) # type: ignore[assignment]\n \"\"\"Apply this function to any object that :meth:`json.dumps` does\n not know how to serialize. It should return a valid JSON type or\n raise a ``TypeError``.\n \"\"\"\n\n ensure_ascii = True\n \"\"\"Replace non-ASCII characters with escape sequences. This may be\n more compatible with some clients, but can be disabled for better\n performance and size.\n \"\"\"\n\n sort_keys = True\n \"\"\"Sort the keys in any serialized dicts. This may be useful for\n some caching situations, but can be disabled for better performance.\n When enabled, keys must all be strings, they are not converted\n before sorting.\n \"\"\"\n\n compact: bool | None = None\n \"\"\"If ``True``, or ``None`` out of debug mode, the :meth:`response`\n output will not add indentation, newlines, or spaces. If ``False``,\n or ``None`` in debug mode, it will use a non-compact representation.\n \"\"\"\n\n mimetype = \"application/json\"\n \"\"\"The mimetype set in :meth:`response`.\"\"\"\n\n def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON to a string.\n\n Keyword arguments are passed to :func:`json.dumps`. Sets some\n parameter defaults from the :attr:`default`,\n :attr:`ensure_ascii`, and :attr:`sort_keys` attributes.\n\n :param obj: The data to serialize.\n :param kwargs: Passed to :func:`json.dumps`.\n \"\"\"\n kwargs.setdefault(\"default\", self.default)\n kwargs.setdefault(\"ensure_ascii\", self.ensure_ascii)\n kwargs.setdefault(\"sort_keys\", self.sort_keys)\n return json.dumps(obj, **kwargs)\n\n def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON from a string or bytes.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: Passed to :func:`json.loads`.\n \"\"\"\n return json.loads(s, **kwargs)\n\n def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with it. The response mimetype\n will be \"application/json\" and can be changed with\n :attr:`mimetype`.\n\n If :attr:`compact` is ``False`` or debug mode is enabled, the\n output will be formatted to be easier to read.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n \"\"\"\n obj = self._prepare_response_obj(args, kwargs)\n dump_args: t.Dict[str, t.Any] = {}\n\n if (self.compact is None and self._app.debug) or self.compact is False:\n dump_args.setdefault(\"indent\", 2)\n else:\n dump_args.setdefault(\"separators\", (\",\", \":\"))\n\n return self._app.response_class(\n f\"{self.dumps(obj, **dump_args)}\\n\", mimetype=self.mimetype\n )\n"},{"className":"TemplateNotFound","col":0,"comment":"Raised if a template does not exist.\n\n .. versionchanged:: 2.11\n If the given name is :class:`Undefined` and no message was\n provided, an :exc:`UndefinedError` is raised.\n ","endLoc":70,"id":304,"nodeType":"Class","startLoc":41,"text":"@implements_to_string\nclass TemplateNotFound(IOError, LookupError, TemplateError):\n \"\"\"Raised if a template does not exist.\n\n .. versionchanged:: 2.11\n If the given name is :class:`Undefined` and no message was\n provided, an :exc:`UndefinedError` is raised.\n \"\"\"\n\n # looks weird, but removes the warning descriptor that just\n # bogusly warns us about message being deprecated\n message = None\n\n def __init__(self, name, message=None):\n IOError.__init__(self, name)\n\n if message is None:\n from .runtime import Undefined\n\n if isinstance(name, Undefined):\n name._fail_with_undefined_error()\n\n message = name\n\n self.message = message\n self.name = name\n self.templates = [name]\n\n def __str__(self):\n return self.message"},{"fileName":"signals.py","filePath":"src/flask","id":305,"nodeType":"File","text":"from __future__ import annotations\n\nimport typing as t\nimport warnings\n\nfrom blinker import Namespace\n\n# This namespace is only for signals provided by Flask itself.\n_signals = Namespace()\n\ntemplate_rendered = _signals.signal(\"template-rendered\")\nbefore_render_template = _signals.signal(\"before-render-template\")\nrequest_started = _signals.signal(\"request-started\")\nrequest_finished = _signals.signal(\"request-finished\")\nrequest_tearing_down = _signals.signal(\"request-tearing-down\")\ngot_request_exception = _signals.signal(\"got-request-exception\")\nappcontext_tearing_down = _signals.signal(\"appcontext-tearing-down\")\nappcontext_pushed = _signals.signal(\"appcontext-pushed\")\nappcontext_popped = _signals.signal(\"appcontext-popped\")\nmessage_flashed = _signals.signal(\"message-flashed\")\n\n\ndef __getattr__(name: str) -> t.Any:\n if name == \"signals_available\":\n warnings.warn(\n \"The 'signals_available' attribute is deprecated and will be removed in\"\n \" Flask 2.4. Signals are always available.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return True\n\n raise AttributeError(name)\n"},{"className":"date","col":0,"comment":"null","endLoc":118,"id":306,"nodeType":"Class","startLoc":50,"text":"class date:\n min: ClassVar[date]\n max: ClassVar[date]\n resolution: ClassVar[timedelta]\n def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ...\n @classmethod\n def fromtimestamp(cls, __timestamp: float) -> Self: ...\n @classmethod\n def today(cls) -> Self: ...\n @classmethod\n def fromordinal(cls, __n: int) -> Self: ...\n @classmethod\n def fromisoformat(cls, __date_string: str) -> Self: ...\n if sys.version_info >= (3, 8):\n @classmethod\n def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ...\n\n @property\n def year(self) -> int: ...\n @property\n def month(self) -> int: ...\n @property\n def day(self) -> int: ...\n def ctime(self) -> str: ...\n # On <3.12, the name of the parameter in the pure-Python implementation\n # didn't match the name in the C implementation,\n # meaning it is only *safe* to pass it as a keyword argument on 3.12+\n if sys.version_info >= (3, 12):\n def strftime(self, format: str) -> str: ...\n else:\n def strftime(self, __format: str) -> str: ...\n\n def __format__(self, __fmt: str) -> str: ...\n def isoformat(self) -> str: ...\n def timetuple(self) -> struct_time: ...\n def toordinal(self) -> int: ...\n def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ...\n def __le__(self, __value: date) -> bool: ...\n def __lt__(self, __value: date) -> bool: ...\n def __ge__(self, __value: date) -> bool: ...\n def __gt__(self, __value: date) -> bool: ...\n def __eq__(self, __value: object) -> bool: ...\n if sys.version_info >= (3, 8):\n def __add__(self, __value: timedelta) -> Self: ...\n def __radd__(self, __value: timedelta) -> Self: ...\n @overload\n def __sub__(self, __value: timedelta) -> Self: ...\n @overload\n def __sub__(self, __value: datetime) -> NoReturn: ...\n @overload\n def __sub__(self: _D, __value: _D) -> timedelta: ...\n else:\n # Prior to Python 3.8, arithmetic operations always returned `date`, even in subclasses\n def __add__(self, __value: timedelta) -> date: ...\n def __radd__(self, __value: timedelta) -> date: ...\n @overload\n def __sub__(self, __value: timedelta) -> date: ...\n @overload\n def __sub__(self, __value: datetime) -> NoReturn: ...\n @overload\n def __sub__(self, __value: date) -> timedelta: ...\n\n def __hash__(self) -> int: ...\n def weekday(self) -> int: ...\n def isoweekday(self) -> int: ...\n if sys.version_info >= (3, 9):\n def isocalendar(self) -> _IsoCalendarDate: ...\n else:\n def isocalendar(self) -> tuple[int, int, int]: ..."},{"fileName":"sessions.py","filePath":"src/flask","id":307,"nodeType":"File","text":"import hashlib\nimport typing as t\nfrom collections.abc import MutableMapping\nfrom datetime import datetime\nfrom datetime import timezone\n\nfrom itsdangerous import BadSignature\nfrom itsdangerous import URLSafeTimedSerializer\nfrom werkzeug.datastructures import CallbackDict\n\nfrom .json.tag import TaggedJSONSerializer\n\nif t.TYPE_CHECKING: # pragma: no cover\n import typing_extensions as te\n from .app import Flask\n from .wrappers import Request, Response\n\n\nclass SessionMixin(MutableMapping):\n \"\"\"Expands a basic dictionary with session attributes.\"\"\"\n\n @property\n def permanent(self) -> bool:\n \"\"\"This reflects the ``'_permanent'`` key in the dict.\"\"\"\n return self.get(\"_permanent\", False)\n\n @permanent.setter\n def permanent(self, value: bool) -> None:\n self[\"_permanent\"] = bool(value)\n\n #: Some implementations can detect whether a session is newly\n #: created, but that is not guaranteed. Use with caution. The mixin\n # default is hard-coded ``False``.\n new = False\n\n #: Some implementations can detect changes to the session and set\n #: this when that happens. The mixin default is hard coded to\n #: ``True``.\n modified = True\n\n #: Some implementations can detect when session data is read or\n #: written and set this when that happens. The mixin default is hard\n #: coded to ``True``.\n accessed = True\n\n\nclass SecureCookieSession(CallbackDict, SessionMixin):\n \"\"\"Base class for sessions based on signed cookies.\n\n This session backend will set the :attr:`modified` and\n :attr:`accessed` attributes. It cannot reliably track whether a\n session is new (vs. empty), so :attr:`new` remains hard coded to\n ``False``.\n \"\"\"\n\n #: When data is changed, this is set to ``True``. Only the session\n #: dictionary itself is tracked; if the session contains mutable\n #: data (for example a nested dict) then this must be set to\n #: ``True`` manually when modifying that data. The session cookie\n #: will only be written to the response if this is ``True``.\n modified = False\n\n #: When data is read or written, this is set to ``True``. Used by\n # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``\n #: header, which allows caching proxies to cache different pages for\n #: different users.\n accessed = False\n\n def __init__(self, initial: t.Any = None) -> None:\n def on_update(self) -> None:\n self.modified = True\n self.accessed = True\n\n super().__init__(initial, on_update)\n\n def __getitem__(self, key: str) -> t.Any:\n self.accessed = True\n return super().__getitem__(key)\n\n def get(self, key: str, default: t.Any = None) -> t.Any:\n self.accessed = True\n return super().get(key, default)\n\n def setdefault(self, key: str, default: t.Any = None) -> t.Any:\n self.accessed = True\n return super().setdefault(key, default)\n\n\nclass NullSession(SecureCookieSession):\n \"\"\"Class used to generate nicer error messages if sessions are not\n available. Will still allow read-only access to the empty session\n but fail on setting.\n \"\"\"\n\n def _fail(self, *args: t.Any, **kwargs: t.Any) -> \"te.NoReturn\":\n raise RuntimeError(\n \"The session is unavailable because no secret \"\n \"key was set. Set the secret_key on the \"\n \"application to something unique and secret.\"\n )\n\n __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail # type: ignore # noqa: B950\n del _fail\n\n\nclass SessionInterface:\n \"\"\"The basic interface you have to implement in order to replace the\n default session interface which uses werkzeug's securecookie\n implementation. The only methods you have to implement are\n :meth:`open_session` and :meth:`save_session`, the others have\n useful defaults which you don't need to change.\n\n The session object returned by the :meth:`open_session` method has to\n provide a dictionary like interface plus the properties and methods\n from the :class:`SessionMixin`. We recommend just subclassing a dict\n and adding that mixin::\n\n class Session(dict, SessionMixin):\n pass\n\n If :meth:`open_session` returns ``None`` Flask will call into\n :meth:`make_null_session` to create a session that acts as replacement\n if the session support cannot work because some requirement is not\n fulfilled. The default :class:`NullSession` class that is created\n will complain that the secret key was not set.\n\n To replace the session interface on an application all you have to do\n is to assign :attr:`flask.Flask.session_interface`::\n\n app = Flask(__name__)\n app.session_interface = MySessionInterface()\n\n Multiple requests with the same session may be sent and handled\n concurrently. When implementing a new session interface, consider\n whether reads or writes to the backing store must be synchronized.\n There is no guarantee on the order in which the session for each\n request is opened or saved, it will occur in the order that requests\n begin and end processing.\n\n .. versionadded:: 0.8\n \"\"\"\n\n #: :meth:`make_null_session` will look here for the class that should\n #: be created when a null session is requested. Likewise the\n #: :meth:`is_null_session` method will perform a typecheck against\n #: this type.\n null_session_class = NullSession\n\n #: A flag that indicates if the session interface is pickle based.\n #: This can be used by Flask extensions to make a decision in regards\n #: to how to deal with the session object.\n #:\n #: .. versionadded:: 0.10\n pickle_based = False\n\n def make_null_session(self, app: \"Flask\") -> NullSession:\n \"\"\"Creates a null session which acts as a replacement object if the\n real session support could not be loaded due to a configuration\n error. This mainly aids the user experience because the job of the\n null session is to still support lookup without complaining but\n modifications are answered with a helpful error message of what\n failed.\n\n This creates an instance of :attr:`null_session_class` by default.\n \"\"\"\n return self.null_session_class()\n\n def is_null_session(self, obj: object) -> bool:\n \"\"\"Checks if a given object is a null session. Null sessions are\n not asked to be saved.\n\n This checks if the object is an instance of :attr:`null_session_class`\n by default.\n \"\"\"\n return isinstance(obj, self.null_session_class)\n\n def get_cookie_name(self, app: \"Flask\") -> str:\n \"\"\"The name of the session cookie. Uses``app.config[\"SESSION_COOKIE_NAME\"]``.\"\"\"\n return app.config[\"SESSION_COOKIE_NAME\"]\n\n def get_cookie_domain(self, app: \"Flask\") -> t.Optional[str]:\n \"\"\"The value of the ``Domain`` parameter on the session cookie. If not set,\n browsers will only send the cookie to the exact domain it was set from.\n Otherwise, they will send it to any subdomain of the given value as well.\n\n Uses the :data:`SESSION_COOKIE_DOMAIN` config.\n\n .. versionchanged:: 2.3\n Not set by default, does not fall back to ``SERVER_NAME``.\n \"\"\"\n rv = app.config[\"SESSION_COOKIE_DOMAIN\"]\n return rv if rv else None\n\n def get_cookie_path(self, app: \"Flask\") -> str:\n \"\"\"Returns the path for which the cookie should be valid. The\n default implementation uses the value from the ``SESSION_COOKIE_PATH``\n config var if it's set, and falls back to ``APPLICATION_ROOT`` or\n uses ``/`` if it's ``None``.\n \"\"\"\n return app.config[\"SESSION_COOKIE_PATH\"] or app.config[\"APPLICATION_ROOT\"]\n\n def get_cookie_httponly(self, app: \"Flask\") -> bool:\n \"\"\"Returns True if the session cookie should be httponly. This\n currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``\n config var.\n \"\"\"\n return app.config[\"SESSION_COOKIE_HTTPONLY\"]\n\n def get_cookie_secure(self, app: \"Flask\") -> bool:\n \"\"\"Returns True if the cookie should be secure. This currently\n just returns the value of the ``SESSION_COOKIE_SECURE`` setting.\n \"\"\"\n return app.config[\"SESSION_COOKIE_SECURE\"]\n\n def get_cookie_samesite(self, app: \"Flask\") -> str:\n \"\"\"Return ``'Strict'`` or ``'Lax'`` if the cookie should use the\n ``SameSite`` attribute. This currently just returns the value of\n the :data:`SESSION_COOKIE_SAMESITE` setting.\n \"\"\"\n return app.config[\"SESSION_COOKIE_SAMESITE\"]\n\n def get_expiration_time(\n self, app: \"Flask\", session: SessionMixin\n ) -> t.Optional[datetime]:\n \"\"\"A helper method that returns an expiration date for the session\n or ``None`` if the session is linked to the browser session. The\n default implementation returns now + the permanent session\n lifetime configured on the application.\n \"\"\"\n if session.permanent:\n return datetime.now(timezone.utc) + app.permanent_session_lifetime\n return None\n\n def should_set_cookie(self, app: \"Flask\", session: SessionMixin) -> bool:\n \"\"\"Used by session backends to determine if a ``Set-Cookie`` header\n should be set for this session cookie for this response. If the session\n has been modified, the cookie is set. If the session is permanent and\n the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is\n always set.\n\n This check is usually skipped if the session was deleted.\n\n .. versionadded:: 0.11\n \"\"\"\n\n return session.modified or (\n session.permanent and app.config[\"SESSION_REFRESH_EACH_REQUEST\"]\n )\n\n def open_session(\n self, app: \"Flask\", request: \"Request\"\n ) -> t.Optional[SessionMixin]:\n \"\"\"This is called at the beginning of each request, after\n pushing the request context, before matching the URL.\n\n This must return an object which implements a dictionary-like\n interface as well as the :class:`SessionMixin` interface.\n\n This will return ``None`` to indicate that loading failed in\n some way that is not immediately an error. The request\n context will fall back to using :meth:`make_null_session`\n in this case.\n \"\"\"\n raise NotImplementedError()\n\n def save_session(\n self, app: \"Flask\", session: SessionMixin, response: \"Response\"\n ) -> None:\n \"\"\"This is called at the end of each request, after generating\n a response, before removing the request context. It is skipped\n if :meth:`is_null_session` returns ``True``.\n \"\"\"\n raise NotImplementedError()\n\n\nsession_json_serializer = TaggedJSONSerializer()\n\n\nclass SecureCookieSessionInterface(SessionInterface):\n \"\"\"The default session interface that stores sessions in signed cookies\n through the :mod:`itsdangerous` module.\n \"\"\"\n\n #: the salt that should be applied on top of the secret key for the\n #: signing of cookie based sessions.\n salt = \"cookie-session\"\n #: the hash function to use for the signature. The default is sha1\n digest_method = staticmethod(hashlib.sha1)\n #: the name of the itsdangerous supported key derivation. The default\n #: is hmac.\n key_derivation = \"hmac\"\n #: A python serializer for the payload. The default is a compact\n #: JSON derived serializer with support for some extra Python types\n #: such as datetime objects or tuples.\n serializer = session_json_serializer\n session_class = SecureCookieSession\n\n def get_signing_serializer(\n self, app: \"Flask\"\n ) -> t.Optional[URLSafeTimedSerializer]:\n if not app.secret_key:\n return None\n signer_kwargs = dict(\n key_derivation=self.key_derivation, digest_method=self.digest_method\n )\n return URLSafeTimedSerializer(\n app.secret_key,\n salt=self.salt,\n serializer=self.serializer,\n signer_kwargs=signer_kwargs,\n )\n\n def open_session(\n self, app: \"Flask\", request: \"Request\"\n ) -> t.Optional[SecureCookieSession]:\n s = self.get_signing_serializer(app)\n if s is None:\n return None\n val = request.cookies.get(self.get_cookie_name(app))\n if not val:\n return self.session_class()\n max_age = int(app.permanent_session_lifetime.total_seconds())\n try:\n data = s.loads(val, max_age=max_age)\n return self.session_class(data)\n except BadSignature:\n return self.session_class()\n\n def save_session(\n self, app: \"Flask\", session: SessionMixin, response: \"Response\"\n ) -> None:\n name = self.get_cookie_name(app)\n domain = self.get_cookie_domain(app)\n path = self.get_cookie_path(app)\n secure = self.get_cookie_secure(app)\n samesite = self.get_cookie_samesite(app)\n httponly = self.get_cookie_httponly(app)\n\n # If the session is modified to be empty, remove the cookie.\n # If the session is empty, return without setting the cookie.\n if not session:\n if session.modified:\n response.delete_cookie(\n name,\n domain=domain,\n path=path,\n secure=secure,\n samesite=samesite,\n httponly=httponly,\n )\n\n return\n\n # Add a \"Vary: Cookie\" header if the session was accessed at all.\n if session.accessed:\n response.vary.add(\"Cookie\")\n\n if not self.should_set_cookie(app, session):\n return\n\n expires = self.get_expiration_time(app, session)\n val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore\n response.set_cookie(\n name,\n val, # type: ignore\n expires=expires,\n httponly=httponly,\n domain=domain,\n path=path,\n secure=secure,\n samesite=samesite,\n )\n"},{"fileName":"blog.py","filePath":"examples/tutorial/flaskr","id":308,"nodeType":"File","text":"from flask import Blueprint\nfrom flask import flash\nfrom flask import g\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\nfrom werkzeug.exceptions import abort\n\nfrom flaskr.auth import login_required\nfrom flaskr.db import get_db\n\nbp = Blueprint(\"blog\", __name__)\n\n\n@bp.route(\"/\")\ndef index():\n \"\"\"Show all the posts, most recent first.\"\"\"\n db = get_db()\n posts = db.execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" ORDER BY created DESC\"\n ).fetchall()\n return render_template(\"blog/index.html\", posts=posts)\n\n\ndef get_post(id, check_author=True):\n \"\"\"Get a post and its author by id.\n\n Checks that the id exists and optionally that the current user is\n the author.\n\n :param id: id of post to get\n :param check_author: require the current user to be the author\n :return: the post with author information\n :raise 404: if a post with the given id doesn't exist\n :raise 403: if the current user isn't the author\n \"\"\"\n post = (\n get_db()\n .execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" WHERE p.id = ?\",\n (id,),\n )\n .fetchone()\n )\n\n if post is None:\n abort(404, f\"Post id {id} doesn't exist.\")\n\n if check_author and post[\"author_id\"] != g.user[\"id\"]:\n abort(403)\n\n return post\n\n\n@bp.route(\"/create\", methods=(\"GET\", \"POST\"))\n@login_required\ndef create():\n \"\"\"Create a new post for the current user.\"\"\"\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)\",\n (title, body, g.user[\"id\"]),\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/create.html\")\n\n\n@bp.route(\"//update\", methods=(\"GET\", \"POST\"))\n@login_required\ndef update(id):\n \"\"\"Update a post if the current user is the author.\"\"\"\n post = get_post(id)\n\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"UPDATE post SET title = ?, body = ? WHERE id = ?\", (title, body, id)\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/update.html\", post=post)\n\n\n@bp.route(\"//delete\", methods=(\"POST\",))\n@login_required\ndef delete(id):\n \"\"\"Delete a post.\n\n Ensures that the post exists and that the logged in user is the\n author of the post.\n \"\"\"\n get_post(id)\n db = get_db()\n db.execute(\"DELETE FROM post WHERE id = ?\", (id,))\n db.commit()\n return redirect(url_for(\"blog.index\"))\n"},{"className":"MutableMapping","col":0,"comment":"null","endLoc":691,"id":309,"nodeType":"Class","startLoc":643,"text":"class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]):\n @abstractmethod\n def __setitem__(self, __key: _KT, __value: _VT) -> None: ...\n @abstractmethod\n def __delitem__(self, __key: _KT) -> None: ...\n def clear(self) -> None: ...\n @overload\n def pop(self, __key: _KT) -> _VT: ...\n @overload\n def pop(self, __key: _KT, default: _VT) -> _VT: ...\n @overload\n def pop(self, __key: _KT, default: _T) -> _VT | _T: ...\n def popitem(self) -> tuple[_KT, _VT]: ...\n # This overload should be allowed only if the value type is compatible with None.\n #\n # Keep the following methods in line with MutableMapping.setdefault, modulo positional-only differences:\n # -- collections.OrderedDict.setdefault\n # -- collections.ChainMap.setdefault\n # -- weakref.WeakKeyDictionary.setdefault\n @overload\n def setdefault(self: MutableMapping[_KT, _T | None], __key: _KT, __default: None = None) -> _T | None: ...\n @overload\n def setdefault(self, __key: _KT, __default: _VT) -> _VT: ...\n # 'update' used to take a Union, but using overloading is better.\n # The second overloaded type here is a bit too general, because\n # Mapping[tuple[_KT, _VT], W] is a subclass of Iterable[tuple[_KT, _VT]],\n # but will always have the behavior of the first overloaded type\n # at runtime, leading to keys of a mix of types _KT and tuple[_KT, _VT].\n # We don't currently have any way of forcing all Mappings to use\n # the first overload, but by using overloading rather than a Union,\n # mypy will commit to using the first overload when the argument is\n # known to be a Mapping with unknown type parameters, which is closer\n # to the behavior we want. See mypy issue #1430.\n #\n # Various mapping classes have __ior__ methods that should be kept roughly in line with .update():\n # -- dict.__ior__\n # -- os._Environ.__ior__\n # -- collections.UserDict.__ior__\n # -- collections.ChainMap.__ior__\n # -- peewee.attrdict.__add__\n # -- peewee.attrdict.__iadd__\n # -- weakref.WeakValueDictionary.__ior__\n # -- weakref.WeakKeyDictionary.__ior__\n @overload\n def update(self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ...\n @overload\n def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ...\n @overload\n def update(self, **kwargs: _VT) -> None: ..."},{"fileName":"auth.py","filePath":"examples/tutorial/flaskr","id":310,"nodeType":"File","text":"import functools\n\nfrom flask import Blueprint\nfrom flask import flash\nfrom flask import g\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import session\nfrom flask import url_for\nfrom werkzeug.security import check_password_hash\nfrom werkzeug.security import generate_password_hash\n\nfrom flaskr.db import get_db\n\nbp = Blueprint(\"auth\", __name__, url_prefix=\"/auth\")\n\n\ndef login_required(view):\n \"\"\"View decorator that redirects anonymous users to the login page.\"\"\"\n\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for(\"auth.login\"))\n\n return view(**kwargs)\n\n return wrapped_view\n\n\n@bp.before_app_request\ndef load_logged_in_user():\n \"\"\"If a user id is stored in the session, load the user object from\n the database into ``g.user``.\"\"\"\n user_id = session.get(\"user_id\")\n\n if user_id is None:\n g.user = None\n else:\n g.user = (\n get_db().execute(\"SELECT * FROM user WHERE id = ?\", (user_id,)).fetchone()\n )\n\n\n@bp.route(\"/register\", methods=(\"GET\", \"POST\"))\ndef register():\n \"\"\"Register a new user.\n\n Validates that the username is not already taken. Hashes the\n password for security.\n \"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n\n if not username:\n error = \"Username is required.\"\n elif not password:\n error = \"Password is required.\"\n\n if error is None:\n try:\n db.execute(\n \"INSERT INTO user (username, password) VALUES (?, ?)\",\n (username, generate_password_hash(password)),\n )\n db.commit()\n except db.IntegrityError:\n # The username was already taken, which caused the\n # commit to fail. Show a validation error.\n error = f\"User {username} is already registered.\"\n else:\n # Success, go to the login page.\n return redirect(url_for(\"auth.login\"))\n\n flash(error)\n\n return render_template(\"auth/register.html\")\n\n\n@bp.route(\"/login\", methods=(\"GET\", \"POST\"))\ndef login():\n \"\"\"Log in a registered user by adding the user id to the session.\"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n user = db.execute(\n \"SELECT * FROM user WHERE username = ?\", (username,)\n ).fetchone()\n\n if user is None:\n error = \"Incorrect username.\"\n elif not check_password_hash(user[\"password\"], password):\n error = \"Incorrect password.\"\n\n if error is None:\n # store the user id in a new session and return to the index\n session.clear()\n session[\"user_id\"] = user[\"id\"]\n return redirect(url_for(\"index\"))\n\n flash(error)\n\n return render_template(\"auth/login.html\")\n\n\n@bp.route(\"/logout\")\ndef logout():\n \"\"\"Clear the current session, including the stored user id.\"\"\"\n session.clear()\n return redirect(url_for(\"index\"))\n"},{"className":"LookupError","col":0,"comment":"null","endLoc":1986,"id":311,"nodeType":"Class","startLoc":1986,"text":"class LookupError(Exception): ..."},{"col":0,"comment":"null","endLoc":33,"header":"def __getattr__(name: str) -> t.Any","id":313,"name":"__getattr__","nodeType":"Function","startLoc":23,"text":"def __getattr__(name: str) -> t.Any:\n if name == \"signals_available\":\n warnings.warn(\n \"The 'signals_available' attribute is deprecated and will be removed in\"\n \" Flask 2.4. Signals are always available.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return True\n\n raise AttributeError(name)"},{"col":0,"comment":"Show all the posts, most recent first.","endLoc":25,"header":"@bp.route(\"/\")\ndef index()","id":314,"name":"index","nodeType":"Function","startLoc":16,"text":"@bp.route(\"/\")\ndef index():\n \"\"\"Show all the posts, most recent first.\"\"\"\n db = get_db()\n posts = db.execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" ORDER BY created DESC\"\n ).fetchall()\n return render_template(\"blog/index.html\", posts=posts)"},{"col":0,"comment":"View decorator that redirects anonymous users to the login page.","endLoc":29,"header":"def login_required(view)","id":316,"name":"login_required","nodeType":"Function","startLoc":19,"text":"def login_required(view):\n \"\"\"View decorator that redirects anonymous users to the login page.\"\"\"\n\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for(\"auth.login\"))\n\n return view(**kwargs)\n\n return wrapped_view"},{"col":0,"comment":"Get a post and its author by id.\n\n Checks that the id exists and optionally that the current user is\n the author.\n\n :param id: id of post to get\n :param check_author: require the current user to be the author\n :return: the post with author information\n :raise 404: if a post with the given id doesn't exist\n :raise 403: if the current user isn't the author\n ","endLoc":57,"header":"def get_post(id, check_author=True)","id":317,"name":"get_post","nodeType":"Function","startLoc":28,"text":"def get_post(id, check_author=True):\n \"\"\"Get a post and its author by id.\n\n Checks that the id exists and optionally that the current user is\n the author.\n\n :param id: id of post to get\n :param check_author: require the current user to be the author\n :return: the post with author information\n :raise 404: if a post with the given id doesn't exist\n :raise 403: if the current user isn't the author\n \"\"\"\n post = (\n get_db()\n .execute(\n \"SELECT p.id, title, body, created, author_id, username\"\n \" FROM post p JOIN user u ON p.author_id = u.id\"\n \" WHERE p.id = ?\",\n (id,),\n )\n .fetchone()\n )\n\n if post is None:\n abort(404, f\"Post id {id} doesn't exist.\")\n\n if check_author and post[\"author_id\"] != g.user[\"id\"]:\n abort(403)\n\n return post"},{"col":4,"comment":"null","endLoc":380,"header":"@overload\n def __init__(self) -> None","id":318,"name":"__init__","nodeType":"Function","startLoc":379,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":382,"header":"@overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None","id":319,"name":"__init__","nodeType":"Function","startLoc":381,"text":"@overload\n def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":384,"header":"@overload\n def __init__(self, __default_factory: Callable[[], _VT] | None) -> None","id":320,"name":"__init__","nodeType":"Function","startLoc":383,"text":"@overload\n def __init__(self, __default_factory: Callable[[], _VT] | None) -> None: ..."},{"col":4,"comment":"null","endLoc":386,"header":"@overload\n def __init__(self: defaultdict[str, _VT], __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None","id":321,"name":"__init__","nodeType":"Function","startLoc":385,"text":"@overload\n def __init__(self: defaultdict[str, _VT], __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":388,"header":"@overload\n def __init__(self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None","id":322,"name":"__init__","nodeType":"Function","startLoc":387,"text":"@overload\n def __init__(self, __default_factory: Callable[[], _VT] | None, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ..."},{"col":0,"comment":"Create a new post for the current user.","endLoc":83,"header":"@bp.route(\"/create\", methods=(\"GET\", \"POST\"))\n@login_required\ndef create()","id":323,"name":"create","nodeType":"Function","startLoc":60,"text":"@bp.route(\"/create\", methods=(\"GET\", \"POST\"))\n@login_required\ndef create():\n \"\"\"Create a new post for the current user.\"\"\"\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)\",\n (title, body, g.user[\"id\"]),\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/create.html\")"},{"col":4,"comment":"null","endLoc":395,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT],\n __default_factory: Callable[[], _VT] | None,\n __map: SupportsKeysAndGetItem[str, _VT],\n **kwargs: _VT,\n ) -> None","id":324,"name":"__init__","nodeType":"Function","startLoc":389,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT],\n __default_factory: Callable[[], _VT] | None,\n __map: SupportsKeysAndGetItem[str, _VT],\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":397,"header":"@overload\n def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None","id":325,"name":"__init__","nodeType":"Function","startLoc":396,"text":"@overload\n def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ..."},{"col":4,"comment":"null","endLoc":404,"header":"@overload\n def __init__(\n self: defaultdict[str, _VT],\n __default_factory: Callable[[], _VT] | None,\n __iterable: Iterable[tuple[str, _VT]],\n **kwargs: _VT,\n ) -> None","id":327,"name":"__init__","nodeType":"Function","startLoc":398,"text":"@overload\n def __init__(\n self: defaultdict[str, _VT],\n __default_factory: Callable[[], _VT] | None,\n __iterable: Iterable[tuple[str, _VT]],\n **kwargs: _VT,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":405,"header":"def __missing__(self, __key: _KT) -> _VT","id":328,"name":"__missing__","nodeType":"Function","startLoc":405,"text":"def __missing__(self, __key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":406,"header":"def __copy__(self) -> Self","id":329,"name":"__copy__","nodeType":"Function","startLoc":406,"text":"def __copy__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":407,"header":"def copy(self) -> Self","id":330,"name":"copy","nodeType":"Function","startLoc":407,"text":"def copy(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":410,"header":"@overload\n def __or__(self, __value: dict[_KT, _VT]) -> Self","id":331,"name":"__or__","nodeType":"Function","startLoc":409,"text":"@overload\n def __or__(self, __value: dict[_KT, _VT]) -> Self: ..."},{"col":8,"comment":"null","endLoc":412,"header":"@overload\n def __or__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]","id":332,"name":"__or__","nodeType":"Function","startLoc":411,"text":"@overload\n def __or__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ..."},{"col":8,"comment":"null","endLoc":414,"header":"@overload\n def __ror__(self, __value: dict[_KT, _VT]) -> Self","id":333,"name":"__ror__","nodeType":"Function","startLoc":413,"text":"@overload\n def __ror__(self, __value: dict[_KT, _VT]) -> Self: ..."},{"col":8,"comment":"null","endLoc":416,"header":"@overload\n def __ror__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]","id":334,"name":"__ror__","nodeType":"Function","startLoc":415,"text":"@overload\n def __ror__(self, __value: dict[_T1, _T2]) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]"},{"attributeType":"() -> _VT | None","col":4,"comment":"null","endLoc":378,"id":335,"name":"default_factory","nodeType":"Attribute","startLoc":378,"text":"default_factory"},{"col":0,"comment":"Update a post if the current user is the author.","endLoc":110,"header":"@bp.route(\"//update\", methods=(\"GET\", \"POST\"))\n@login_required\ndef update(id)","id":338,"name":"update","nodeType":"Function","startLoc":86,"text":"@bp.route(\"//update\", methods=(\"GET\", \"POST\"))\n@login_required\ndef update(id):\n \"\"\"Update a post if the current user is the author.\"\"\"\n post = get_post(id)\n\n if request.method == \"POST\":\n title = request.form[\"title\"]\n body = request.form[\"body\"]\n error = None\n\n if not title:\n error = \"Title is required.\"\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n \"UPDATE post SET title = ?, body = ? WHERE id = ?\", (title, body, id)\n )\n db.commit()\n return redirect(url_for(\"blog.index\"))\n\n return render_template(\"blog/update.html\", post=post)"},{"col":0,"comment":"If a user id is stored in the session, load the user object from\n the database into ``g.user``.","endLoc":43,"header":"@bp.before_app_request\ndef load_logged_in_user()","id":339,"name":"load_logged_in_user","nodeType":"Function","startLoc":32,"text":"@bp.before_app_request\ndef load_logged_in_user():\n \"\"\"If a user id is stored in the session, load the user object from\n the database into ``g.user``.\"\"\"\n user_id = session.get(\"user_id\")\n\n if user_id is None:\n g.user = None\n else:\n g.user = (\n get_db().execute(\"SELECT * FROM user WHERE id = ?\", (user_id,)).fetchone()\n )"},{"col":0,"comment":"Register a new user.\n\n Validates that the username is not already taken. Hashes the\n password for security.\n ","endLoc":81,"header":"@bp.route(\"/register\", methods=(\"GET\", \"POST\"))\ndef register()","id":340,"name":"register","nodeType":"Function","startLoc":46,"text":"@bp.route(\"/register\", methods=(\"GET\", \"POST\"))\ndef register():\n \"\"\"Register a new user.\n\n Validates that the username is not already taken. Hashes the\n password for security.\n \"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n\n if not username:\n error = \"Username is required.\"\n elif not password:\n error = \"Password is required.\"\n\n if error is None:\n try:\n db.execute(\n \"INSERT INTO user (username, password) VALUES (?, ?)\",\n (username, generate_password_hash(password)),\n )\n db.commit()\n except db.IntegrityError:\n # The username was already taken, which caused the\n # commit to fail. Show a validation error.\n error = f\"User {username} is already registered.\"\n else:\n # Success, go to the login page.\n return redirect(url_for(\"auth.login\"))\n\n flash(error)\n\n return render_template(\"auth/register.html\")"},{"col":0,"comment":"Delete a post.\n\n Ensures that the post exists and that the logged in user is the\n author of the post.\n ","endLoc":125,"header":"@bp.route(\"//delete\", methods=(\"POST\",))\n@login_required\ndef delete(id)","id":341,"name":"delete","nodeType":"Function","startLoc":113,"text":"@bp.route(\"//delete\", methods=(\"POST\",))\n@login_required\ndef delete(id):\n \"\"\"Delete a post.\n\n Ensures that the post exists and that the logged in user is the\n author of the post.\n \"\"\"\n get_post(id)\n db = get_db()\n db.execute(\"DELETE FROM post WHERE id = ?\", (id,))\n db.commit()\n return redirect(url_for(\"blog.index\"))"},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":342,"name":"bp","nodeType":"Attribute","startLoc":13,"text":"bp"},{"col":0,"comment":"","endLoc":1,"header":"blog.py#","id":343,"name":"","nodeType":"Function","startLoc":1,"text":"bp = Blueprint(\"blog\", __name__)"},{"col":0,"comment":"Log in a registered user by adding the user id to the session.","endLoc":109,"header":"@bp.route(\"/login\", methods=(\"GET\", \"POST\"))\ndef login()","id":345,"name":"login","nodeType":"Function","startLoc":84,"text":"@bp.route(\"/login\", methods=(\"GET\", \"POST\"))\ndef login():\n \"\"\"Log in a registered user by adding the user id to the session.\"\"\"\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password = request.form[\"password\"]\n db = get_db()\n error = None\n user = db.execute(\n \"SELECT * FROM user WHERE username = ?\", (username,)\n ).fetchone()\n\n if user is None:\n error = \"Incorrect username.\"\n elif not check_password_hash(user[\"password\"], password):\n error = \"Incorrect password.\"\n\n if error is None:\n # store the user id in a new session and return to the index\n session.clear()\n session[\"user_id\"] = user[\"id\"]\n return redirect(url_for(\"index\"))\n\n flash(error)\n\n return render_template(\"auth/login.html\")"},{"className":"timedelta","col":0,"comment":"null","endLoc":227,"id":346,"nodeType":"Class","startLoc":181,"text":"class timedelta:\n min: ClassVar[timedelta]\n max: ClassVar[timedelta]\n resolution: ClassVar[timedelta]\n def __new__(\n cls,\n days: float = ...,\n seconds: float = ...,\n microseconds: float = ...,\n milliseconds: float = ...,\n minutes: float = ...,\n hours: float = ...,\n weeks: float = ...,\n ) -> Self: ...\n @property\n def days(self) -> int: ...\n @property\n def seconds(self) -> int: ...\n @property\n def microseconds(self) -> int: ...\n def total_seconds(self) -> float: ...\n def __add__(self, __value: timedelta) -> timedelta: ...\n def __radd__(self, __value: timedelta) -> timedelta: ...\n def __sub__(self, __value: timedelta) -> timedelta: ...\n def __rsub__(self, __value: timedelta) -> timedelta: ...\n def __neg__(self) -> timedelta: ...\n def __pos__(self) -> timedelta: ...\n def __abs__(self) -> timedelta: ...\n def __mul__(self, __value: float) -> timedelta: ...\n def __rmul__(self, __value: float) -> timedelta: ...\n @overload\n def __floordiv__(self, __value: timedelta) -> int: ...\n @overload\n def __floordiv__(self, __value: int) -> timedelta: ...\n @overload\n def __truediv__(self, __value: timedelta) -> float: ...\n @overload\n def __truediv__(self, __value: float) -> timedelta: ...\n def __mod__(self, __value: timedelta) -> timedelta: ...\n def __divmod__(self, __value: timedelta) -> tuple[int, timedelta]: ...\n def __le__(self, __value: timedelta) -> bool: ...\n def __lt__(self, __value: timedelta) -> bool: ...\n def __ge__(self, __value: timedelta) -> bool: ...\n def __gt__(self, __value: timedelta) -> bool: ...\n def __eq__(self, __value: object) -> bool: ...\n def __bool__(self) -> bool: ...\n def __hash__(self) -> int: ..."},{"col":0,"comment":"Clear the current session, including the stored user id.","endLoc":116,"header":"@bp.route(\"/logout\")\ndef logout()","id":347,"name":"logout","nodeType":"Function","startLoc":112,"text":"@bp.route(\"/logout\")\ndef logout():\n \"\"\"Clear the current session, including the stored user id.\"\"\"\n session.clear()\n return redirect(url_for(\"index\"))"},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":348,"name":"bp","nodeType":"Attribute","startLoc":16,"text":"bp"},{"col":0,"comment":"","endLoc":1,"header":"auth.py#","id":349,"name":"","nodeType":"Function","startLoc":1,"text":"bp = Blueprint(\"auth\", __name__, url_prefix=\"/auth\")"},{"id":350,"name":"tests/test_apps/blueprintapp/apps/admin/static","nodeType":"Package"},{"id":351,"name":"test.txt","nodeType":"TextFile","path":"tests/test_apps/blueprintapp/apps/admin/static","text":"Admin File\n"},{"fileName":"test_cli.py","filePath":"tests","id":352,"nodeType":"File","text":"# This file was part of Flask-CLI and was modified under the terms of\n# its Revised BSD License. Copyright © 2015 CERN.\nimport os\nimport ssl\nimport sys\nimport types\nfrom functools import partial\nfrom pathlib import Path\n\nimport click\nimport pytest\nfrom _pytest.monkeypatch import notset\nfrom click.testing import CliRunner\n\nfrom flask import Blueprint\nfrom flask import current_app\nfrom flask import Flask\nfrom flask.cli import AppGroup\nfrom flask.cli import find_best_app\nfrom flask.cli import FlaskGroup\nfrom flask.cli import get_version\nfrom flask.cli import load_dotenv\nfrom flask.cli import locate_app\nfrom flask.cli import NoAppException\nfrom flask.cli import prepare_import\nfrom flask.cli import run_command\nfrom flask.cli import ScriptInfo\nfrom flask.cli import with_appcontext\n\ncwd = Path.cwd()\ntest_path = (Path(__file__) / \"..\" / \"test_apps\").resolve()\n\n\n@pytest.fixture\ndef runner():\n return CliRunner()\n\n\ndef test_cli_name(test_apps):\n \"\"\"Make sure the CLI object's name is the app's name and not the app itself\"\"\"\n from cliapp.app import testapp\n\n assert testapp.cli.name == testapp.name\n\n\ndef test_find_best_app(test_apps):\n class Module:\n app = Flask(\"appname\")\n\n assert find_best_app(Module) == Module.app\n\n class Module:\n application = Flask(\"appname\")\n\n assert find_best_app(Module) == Module.application\n\n class Module:\n myapp = Flask(\"appname\")\n\n assert find_best_app(Module) == Module.myapp\n\n class Module:\n @staticmethod\n def create_app():\n return Flask(\"appname\")\n\n app = find_best_app(Module)\n assert isinstance(app, Flask)\n assert app.name == \"appname\"\n\n class Module:\n @staticmethod\n def create_app(**kwargs):\n return Flask(\"appname\")\n\n app = find_best_app(Module)\n assert isinstance(app, Flask)\n assert app.name == \"appname\"\n\n class Module:\n @staticmethod\n def make_app():\n return Flask(\"appname\")\n\n app = find_best_app(Module)\n assert isinstance(app, Flask)\n assert app.name == \"appname\"\n\n class Module:\n myapp = Flask(\"appname1\")\n\n @staticmethod\n def create_app():\n return Flask(\"appname2\")\n\n assert find_best_app(Module) == Module.myapp\n\n class Module:\n myapp = Flask(\"appname1\")\n\n @staticmethod\n def create_app():\n return Flask(\"appname2\")\n\n assert find_best_app(Module) == Module.myapp\n\n class Module:\n pass\n\n pytest.raises(NoAppException, find_best_app, Module)\n\n class Module:\n myapp1 = Flask(\"appname1\")\n myapp2 = Flask(\"appname2\")\n\n pytest.raises(NoAppException, find_best_app, Module)\n\n class Module:\n @staticmethod\n def create_app(foo, bar):\n return Flask(\"appname2\")\n\n pytest.raises(NoAppException, find_best_app, Module)\n\n class Module:\n @staticmethod\n def create_app():\n raise TypeError(\"bad bad factory!\")\n\n pytest.raises(TypeError, find_best_app, Module)\n\n\n@pytest.mark.parametrize(\n \"value,path,result\",\n (\n (\"test\", cwd, \"test\"),\n (\"test.py\", cwd, \"test\"),\n (\"a/test\", cwd / \"a\", \"test\"),\n (\"test/__init__.py\", cwd, \"test\"),\n (\"test/__init__\", cwd, \"test\"),\n # nested package\n (\n test_path / \"cliapp\" / \"inner1\" / \"__init__\",\n test_path,\n \"cliapp.inner1\",\n ),\n (\n test_path / \"cliapp\" / \"inner1\" / \"inner2\",\n test_path,\n \"cliapp.inner1.inner2\",\n ),\n # dotted name\n (\"test.a.b\", cwd, \"test.a.b\"),\n (test_path / \"cliapp.app\", test_path, \"cliapp.app\"),\n # not a Python file, will be caught during import\n (test_path / \"cliapp\" / \"message.txt\", test_path, \"cliapp.message.txt\"),\n ),\n)\ndef test_prepare_import(request, value, path, result):\n \"\"\"Expect the correct path to be set and the correct import and app names\n to be returned.\n\n :func:`prepare_exec_for_file` has a side effect where the parent directory\n of the given import is added to :data:`sys.path`. This is reset after the\n test runs.\n \"\"\"\n original_path = sys.path[:]\n\n def reset_path():\n sys.path[:] = original_path\n\n request.addfinalizer(reset_path)\n\n assert prepare_import(value) == result\n assert sys.path[0] == str(path)\n\n\n@pytest.mark.parametrize(\n \"iname,aname,result\",\n (\n (\"cliapp.app\", None, \"testapp\"),\n (\"cliapp.app\", \"testapp\", \"testapp\"),\n (\"cliapp.factory\", None, \"app\"),\n (\"cliapp.factory\", \"create_app\", \"app\"),\n (\"cliapp.factory\", \"create_app()\", \"app\"),\n (\"cliapp.factory\", 'create_app2(\"foo\", \"bar\")', \"app2_foo_bar\"),\n # trailing comma space\n (\"cliapp.factory\", 'create_app2(\"foo\", \"bar\", )', \"app2_foo_bar\"),\n # strip whitespace\n (\"cliapp.factory\", \" create_app () \", \"app\"),\n ),\n)\ndef test_locate_app(test_apps, iname, aname, result):\n assert locate_app(iname, aname).name == result\n\n\n@pytest.mark.parametrize(\n \"iname,aname\",\n (\n (\"notanapp.py\", None),\n (\"cliapp/app\", None),\n (\"cliapp.app\", \"notanapp\"),\n # not enough arguments\n (\"cliapp.factory\", 'create_app2(\"foo\")'),\n # invalid identifier\n (\"cliapp.factory\", \"create_app(\"),\n # no app returned\n (\"cliapp.factory\", \"no_app\"),\n # nested import error\n (\"cliapp.importerrorapp\", None),\n # not a Python file\n (\"cliapp.message.txt\", None),\n ),\n)\ndef test_locate_app_raises(test_apps, iname, aname):\n with pytest.raises(NoAppException):\n locate_app(iname, aname)\n\n\ndef test_locate_app_suppress_raise(test_apps):\n app = locate_app(\"notanapp.py\", None, raise_if_not_found=False)\n assert app is None\n\n # only direct import error is suppressed\n with pytest.raises(NoAppException):\n locate_app(\"cliapp.importerrorapp\", None, raise_if_not_found=False)\n\n\ndef test_get_version(test_apps, capsys):\n from flask import __version__ as flask_version\n from werkzeug import __version__ as werkzeug_version\n from platform import python_version\n\n class MockCtx:\n resilient_parsing = False\n color = None\n\n def exit(self):\n return\n\n ctx = MockCtx()\n get_version(ctx, None, \"test\")\n out, err = capsys.readouterr()\n assert f\"Python {python_version()}\" in out\n assert f\"Flask {flask_version}\" in out\n assert f\"Werkzeug {werkzeug_version}\" in out\n\n\ndef test_scriptinfo(test_apps, monkeypatch):\n obj = ScriptInfo(app_import_path=\"cliapp.app:testapp\")\n app = obj.load_app()\n assert app.name == \"testapp\"\n assert obj.load_app() is app\n\n # import app with module's absolute path\n cli_app_path = str(test_path / \"cliapp\" / \"app.py\")\n\n obj = ScriptInfo(app_import_path=cli_app_path)\n app = obj.load_app()\n assert app.name == \"testapp\"\n assert obj.load_app() is app\n obj = ScriptInfo(app_import_path=f\"{cli_app_path}:testapp\")\n app = obj.load_app()\n assert app.name == \"testapp\"\n assert obj.load_app() is app\n\n def create_app():\n return Flask(\"createapp\")\n\n obj = ScriptInfo(create_app=create_app)\n app = obj.load_app()\n assert app.name == \"createapp\"\n assert obj.load_app() is app\n\n obj = ScriptInfo()\n pytest.raises(NoAppException, obj.load_app)\n\n # import app from wsgi.py in current directory\n monkeypatch.chdir(test_path / \"helloworld\")\n obj = ScriptInfo()\n app = obj.load_app()\n assert app.name == \"hello\"\n\n # import app from app.py in current directory\n monkeypatch.chdir(test_path / \"cliapp\")\n obj = ScriptInfo()\n app = obj.load_app()\n assert app.name == \"testapp\"\n\n\ndef test_app_cli_has_app_context(app, runner):\n def _param_cb(ctx, param, value):\n # current_app should be available in parameter callbacks\n return bool(current_app)\n\n @app.cli.command()\n @click.argument(\"value\", callback=_param_cb)\n def check(value):\n app = click.get_current_context().obj.load_app()\n # the loaded app should be the same as current_app\n same_app = current_app._get_current_object() is app\n return same_app, value\n\n cli = FlaskGroup(create_app=lambda: app)\n result = runner.invoke(cli, [\"check\", \"x\"], standalone_mode=False)\n assert result.return_value == (True, True)\n\n\ndef test_with_appcontext(runner):\n @click.command()\n @with_appcontext\n def testcmd():\n click.echo(current_app.name)\n\n obj = ScriptInfo(create_app=lambda: Flask(\"testapp\"))\n\n result = runner.invoke(testcmd, obj=obj)\n assert result.exit_code == 0\n assert result.output == \"testapp\\n\"\n\n\ndef test_appgroup_app_context(runner):\n @click.group(cls=AppGroup)\n def cli():\n pass\n\n @cli.command()\n def test():\n click.echo(current_app.name)\n\n @cli.group()\n def subgroup():\n pass\n\n @subgroup.command()\n def test2():\n click.echo(current_app.name)\n\n obj = ScriptInfo(create_app=lambda: Flask(\"testappgroup\"))\n\n result = runner.invoke(cli, [\"test\"], obj=obj)\n assert result.exit_code == 0\n assert result.output == \"testappgroup\\n\"\n\n result = runner.invoke(cli, [\"subgroup\", \"test2\"], obj=obj)\n assert result.exit_code == 0\n assert result.output == \"testappgroup\\n\"\n\n\ndef test_flaskgroup_app_context(runner):\n def create_app():\n return Flask(\"flaskgroup\")\n\n @click.group(cls=FlaskGroup, create_app=create_app)\n def cli(**params):\n pass\n\n @cli.command()\n def test():\n click.echo(current_app.name)\n\n result = runner.invoke(cli, [\"test\"])\n assert result.exit_code == 0\n assert result.output == \"flaskgroup\\n\"\n\n\n@pytest.mark.parametrize(\"set_debug_flag\", (True, False))\ndef test_flaskgroup_debug(runner, set_debug_flag):\n def create_app():\n app = Flask(\"flaskgroup\")\n app.debug = True\n return app\n\n @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)\n def cli(**params):\n pass\n\n @cli.command()\n def test():\n click.echo(str(current_app.debug))\n\n result = runner.invoke(cli, [\"test\"])\n assert result.exit_code == 0\n assert result.output == f\"{not set_debug_flag}\\n\"\n\n\ndef test_flaskgroup_nested(app, runner):\n cli = click.Group(\"cli\")\n flask_group = FlaskGroup(name=\"flask\", create_app=lambda: app)\n cli.add_command(flask_group)\n\n @flask_group.command()\n def show():\n click.echo(current_app.name)\n\n result = runner.invoke(cli, [\"flask\", \"show\"])\n assert result.output == \"flask_test\\n\"\n\n\ndef test_no_command_echo_loading_error():\n from flask.cli import cli\n\n runner = CliRunner(mix_stderr=False)\n result = runner.invoke(cli, [\"missing\"])\n assert result.exit_code == 2\n assert \"FLASK_APP\" in result.stderr\n assert \"Usage:\" in result.stderr\n\n\ndef test_help_echo_loading_error():\n from flask.cli import cli\n\n runner = CliRunner(mix_stderr=False)\n result = runner.invoke(cli, [\"--help\"])\n assert result.exit_code == 0\n assert \"FLASK_APP\" in result.stderr\n assert \"Usage:\" in result.stdout\n\n\ndef test_help_echo_exception():\n def create_app():\n raise Exception(\"oh no\")\n\n cli = FlaskGroup(create_app=create_app)\n runner = CliRunner(mix_stderr=False)\n result = runner.invoke(cli, [\"--help\"])\n assert result.exit_code == 0\n assert \"Exception: oh no\" in result.stderr\n assert \"Usage:\" in result.stdout\n\n\nclass TestRoutes:\n @pytest.fixture\n def app(self):\n app = Flask(__name__)\n app.testing = True\n\n @app.route(\"/get_post//\", methods=[\"GET\", \"POST\"])\n def yyy_get_post(x, y):\n pass\n\n @app.route(\"/zzz_post\", methods=[\"POST\"])\n def aaa_post():\n pass\n\n return app\n\n @pytest.fixture\n def invoke(self, app, runner):\n cli = FlaskGroup(create_app=lambda: app)\n return partial(runner.invoke, cli)\n\n @pytest.fixture\n def invoke_no_routes(self, runner):\n def create_app():\n app = Flask(__name__, static_folder=None)\n app.testing = True\n\n return app\n\n cli = FlaskGroup(create_app=create_app)\n return partial(runner.invoke, cli)\n\n def expect_order(self, order, output):\n # skip the header and match the start of each row\n for expect, line in zip(order, output.splitlines()[2:]):\n # do this instead of startswith for nicer pytest output\n assert line[: len(expect)] == expect\n\n def test_simple(self, invoke):\n result = invoke([\"routes\"])\n assert result.exit_code == 0\n self.expect_order([\"aaa_post\", \"static\", \"yyy_get_post\"], result.output)\n\n def test_sort(self, app, invoke):\n default_output = invoke([\"routes\"]).output\n endpoint_output = invoke([\"routes\", \"-s\", \"endpoint\"]).output\n assert default_output == endpoint_output\n self.expect_order(\n [\"static\", \"yyy_get_post\", \"aaa_post\"],\n invoke([\"routes\", \"-s\", \"methods\"]).output,\n )\n self.expect_order(\n [\"yyy_get_post\", \"static\", \"aaa_post\"],\n invoke([\"routes\", \"-s\", \"rule\"]).output,\n )\n match_order = [r.endpoint for r in app.url_map.iter_rules()]\n self.expect_order(match_order, invoke([\"routes\", \"-s\", \"match\"]).output)\n\n def test_all_methods(self, invoke):\n output = invoke([\"routes\"]).output\n assert \"GET, HEAD, OPTIONS, POST\" not in output\n output = invoke([\"routes\", \"--all-methods\"]).output\n assert \"GET, HEAD, OPTIONS, POST\" in output\n\n def test_no_routes(self, invoke_no_routes):\n result = invoke_no_routes([\"routes\"])\n assert result.exit_code == 0\n assert \"No routes were registered.\" in result.output\n\n\ndef dotenv_not_available():\n try:\n import dotenv # noqa: F401\n except ImportError:\n return True\n\n return False\n\n\nneed_dotenv = pytest.mark.skipif(\n dotenv_not_available(), reason=\"dotenv is not installed\"\n)\n\n\n@need_dotenv\ndef test_load_dotenv(monkeypatch):\n # can't use monkeypatch.delitem since the keys don't exist yet\n for item in (\"FOO\", \"BAR\", \"SPAM\", \"HAM\"):\n monkeypatch._setitem.append((os.environ, item, notset))\n\n monkeypatch.setenv(\"EGGS\", \"3\")\n monkeypatch.chdir(test_path)\n assert load_dotenv()\n assert Path.cwd() == test_path\n # .flaskenv doesn't overwrite .env\n assert os.environ[\"FOO\"] == \"env\"\n # set only in .flaskenv\n assert os.environ[\"BAR\"] == \"bar\"\n # set only in .env\n assert os.environ[\"SPAM\"] == \"1\"\n # set manually, files don't overwrite\n assert os.environ[\"EGGS\"] == \"3\"\n # test env file encoding\n assert os.environ[\"HAM\"] == \"火腿\"\n # Non existent file should not load\n assert not load_dotenv(\"non-existent-file\")\n\n\n@need_dotenv\ndef test_dotenv_path(monkeypatch):\n for item in (\"FOO\", \"BAR\", \"EGGS\"):\n monkeypatch._setitem.append((os.environ, item, notset))\n\n load_dotenv(test_path / \".flaskenv\")\n assert Path.cwd() == cwd\n assert \"FOO\" in os.environ\n\n\ndef test_dotenv_optional(monkeypatch):\n monkeypatch.setitem(sys.modules, \"dotenv\", None)\n monkeypatch.chdir(test_path)\n load_dotenv()\n assert \"FOO\" not in os.environ\n\n\n@need_dotenv\ndef test_disable_dotenv_from_env(monkeypatch, runner):\n monkeypatch.chdir(test_path)\n monkeypatch.setitem(os.environ, \"FLASK_SKIP_DOTENV\", \"1\")\n runner.invoke(FlaskGroup())\n assert \"FOO\" not in os.environ\n\n\ndef test_run_cert_path():\n # no key\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--cert\", __file__])\n\n # no cert\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--key\", __file__])\n\n # cert specified first\n ctx = run_command.make_context(\"run\", [\"--cert\", __file__, \"--key\", __file__])\n assert ctx.params[\"cert\"] == (__file__, __file__)\n\n # key specified first\n ctx = run_command.make_context(\"run\", [\"--key\", __file__, \"--cert\", __file__])\n assert ctx.params[\"cert\"] == (__file__, __file__)\n\n\ndef test_run_cert_adhoc(monkeypatch):\n monkeypatch.setitem(sys.modules, \"cryptography\", None)\n\n # cryptography not installed\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--cert\", \"adhoc\"])\n\n # cryptography installed\n monkeypatch.setitem(sys.modules, \"cryptography\", types.ModuleType(\"cryptography\"))\n ctx = run_command.make_context(\"run\", [\"--cert\", \"adhoc\"])\n assert ctx.params[\"cert\"] == \"adhoc\"\n\n # no key with adhoc\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--cert\", \"adhoc\", \"--key\", __file__])\n\n\ndef test_run_cert_import(monkeypatch):\n monkeypatch.setitem(sys.modules, \"not_here\", None)\n\n # ImportError\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--cert\", \"not_here\"])\n\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--cert\", \"flask\"])\n\n # SSLContext\n ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n\n monkeypatch.setitem(sys.modules, \"ssl_context\", ssl_context)\n ctx = run_command.make_context(\"run\", [\"--cert\", \"ssl_context\"])\n assert ctx.params[\"cert\"] is ssl_context\n\n # no --key with SSLContext\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--cert\", \"ssl_context\", \"--key\", __file__])\n\n\ndef test_run_cert_no_ssl(monkeypatch):\n monkeypatch.setitem(sys.modules, \"ssl\", None)\n\n with pytest.raises(click.BadParameter):\n run_command.make_context(\"run\", [\"--cert\", \"not_here\"])\n\n\ndef test_cli_blueprints(app):\n \"\"\"Test blueprint commands register correctly to the application\"\"\"\n custom = Blueprint(\"custom\", __name__, cli_group=\"customized\")\n nested = Blueprint(\"nested\", __name__)\n merged = Blueprint(\"merged\", __name__, cli_group=None)\n late = Blueprint(\"late\", __name__)\n\n @custom.cli.command(\"custom\")\n def custom_command():\n click.echo(\"custom_result\")\n\n @nested.cli.command(\"nested\")\n def nested_command():\n click.echo(\"nested_result\")\n\n @merged.cli.command(\"merged\")\n def merged_command():\n click.echo(\"merged_result\")\n\n @late.cli.command(\"late\")\n def late_command():\n click.echo(\"late_result\")\n\n app.register_blueprint(custom)\n app.register_blueprint(nested)\n app.register_blueprint(merged)\n app.register_blueprint(late, cli_group=\"late_registration\")\n\n app_runner = app.test_cli_runner()\n\n result = app_runner.invoke(args=[\"customized\", \"custom\"])\n assert \"custom_result\" in result.output\n\n result = app_runner.invoke(args=[\"nested\", \"nested\"])\n assert \"nested_result\" in result.output\n\n result = app_runner.invoke(args=[\"merged\"])\n assert \"merged_result\" in result.output\n\n result = app_runner.invoke(args=[\"late_registration\", \"late\"])\n assert \"late_result\" in result.output\n\n\ndef test_cli_empty(app):\n \"\"\"If a Blueprint's CLI group is empty, do not register it.\"\"\"\n bp = Blueprint(\"blue\", __name__, cli_group=\"blue\")\n app.register_blueprint(bp)\n\n result = app.test_cli_runner().invoke(args=[\"blue\", \"--help\"])\n assert result.exit_code == 2, f\"Unexpected success:\\n\\n{result.output}\"\n"},{"className":"partial","col":0,"comment":"null","endLoc":139,"id":353,"nodeType":"Class","startLoc":129,"text":"class partial(Generic[_T]):\n @property\n def func(self) -> Callable[..., _T]: ...\n @property\n def args(self) -> tuple[Any, ...]: ...\n @property\n def keywords(self) -> dict[str, Any]: ...\n def __new__(cls, __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self: ...\n def __call__(__self, *args: Any, **kwargs: Any) -> _T: ...\n if sys.version_info >= (3, 9):\n def __class_getitem__(cls, item: Any) -> GenericAlias: ..."},{"id":354,"name":"views.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nBlueprints and Views\n====================\n\nA view function is the code you write to respond to requests to your\napplication. Flask uses patterns to match the incoming request URL to\nthe view that should handle it. The view returns data that Flask turns\ninto an outgoing response. Flask can also go the other direction and\ngenerate a URL to a view based on its name and arguments.\n\n\nCreate a Blueprint\n------------------\n\nA :class:`Blueprint` is a way to organize a group of related views and\nother code. Rather than registering views and other code directly with\nan application, they are registered with a blueprint. Then the blueprint\nis registered with the application when it is available in the factory\nfunction.\n\nFlaskr will have two blueprints, one for authentication functions and\none for the blog posts functions. The code for each blueprint will go\nin a separate module. Since the blog needs to know about authentication,\nyou'll write the authentication one first.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n import functools\n\n from flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for\n )\n from werkzeug.security import check_password_hash, generate_password_hash\n\n from flaskr.db import get_db\n\n bp = Blueprint('auth', __name__, url_prefix='/auth')\n\nThis creates a :class:`Blueprint` named ``'auth'``. Like the application\nobject, the blueprint needs to know where it's defined, so ``__name__``\nis passed as the second argument. The ``url_prefix`` will be prepended\nto all the URLs associated with the blueprint.\n\nImport and register the blueprint from the factory using\n:meth:`app.register_blueprint() `. Place the\nnew code at the end of the factory function before returning the app.\n\n.. code-block:: python\n :caption: ``flaskr/__init__.py``\n\n def create_app():\n app = ...\n # existing code omitted\n\n from . import auth\n app.register_blueprint(auth.bp)\n\n return app\n\nThe authentication blueprint will have views to register new users and\nto log in and log out.\n\n\nThe First View: Register\n------------------------\n\nWhen the user visits the ``/auth/register`` URL, the ``register`` view\nwill return `HTML`_ with a form for them to fill out. When they submit\nthe form, it will validate their input and either show the form again\nwith an error message or create the new user and go to the login page.\n\n.. _HTML: https://developer.mozilla.org/docs/Web/HTML\n\nFor now you will just write the view code. On the next page, you'll\nwrite templates to generate the HTML form.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.route('/register', methods=('GET', 'POST'))\n def register():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n db = get_db()\n error = None\n\n if not username:\n error = 'Username is required.'\n elif not password:\n error = 'Password is required.'\n\n if error is None:\n try:\n db.execute(\n \"INSERT INTO user (username, password) VALUES (?, ?)\",\n (username, generate_password_hash(password)),\n )\n db.commit()\n except db.IntegrityError:\n error = f\"User {username} is already registered.\"\n else:\n return redirect(url_for(\"auth.login\"))\n\n flash(error)\n\n return render_template('auth/register.html')\n\nHere's what the ``register`` view function is doing:\n\n#. :meth:`@bp.route ` associates the URL ``/register``\n with the ``register`` view function. When Flask receives a request\n to ``/auth/register``, it will call the ``register`` view and use\n the return value as the response.\n\n#. If the user submitted the form,\n :attr:`request.method ` will be ``'POST'``. In this\n case, start validating the input.\n\n#. :attr:`request.form ` is a special type of\n :class:`dict` mapping submitted form keys and values. The user will\n input their ``username`` and ``password``.\n\n#. Validate that ``username`` and ``password`` are not empty.\n\n#. If validation succeeds, insert the new user data into the database.\n\n - :meth:`db.execute ` takes a SQL\n query with ``?`` placeholders for any user input, and a tuple of\n values to replace the placeholders with. The database library\n will take care of escaping the values so you are not vulnerable\n to a *SQL injection attack*.\n\n - For security, passwords should never be stored in the database\n directly. Instead,\n :func:`~werkzeug.security.generate_password_hash` is used to\n securely hash the password, and that hash is stored. Since this\n query modifies data,\n :meth:`db.commit() ` needs to be\n called afterwards to save the changes.\n\n - An :exc:`sqlite3.IntegrityError` will occur if the username\n already exists, which should be shown to the user as another\n validation error.\n\n#. After storing the user, they are redirected to the login page.\n :func:`url_for` generates the URL for the login view based on its\n name. This is preferable to writing the URL directly as it allows\n you to change the URL later without changing all code that links to\n it. :func:`redirect` generates a redirect response to the generated\n URL.\n\n#. If validation fails, the error is shown to the user. :func:`flash`\n stores messages that can be retrieved when rendering the template.\n\n#. When the user initially navigates to ``auth/register``, or\n there was a validation error, an HTML page with the registration\n form should be shown. :func:`render_template` will render a template\n containing the HTML, which you'll write in the next step of the\n tutorial.\n\n\nLogin\n-----\n\nThis view follows the same pattern as the ``register`` view above.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.route('/login', methods=('GET', 'POST'))\n def login():\n if request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n db = get_db()\n error = None\n user = db.execute(\n 'SELECT * FROM user WHERE username = ?', (username,)\n ).fetchone()\n\n if user is None:\n error = 'Incorrect username.'\n elif not check_password_hash(user['password'], password):\n error = 'Incorrect password.'\n\n if error is None:\n session.clear()\n session['user_id'] = user['id']\n return redirect(url_for('index'))\n\n flash(error)\n\n return render_template('auth/login.html')\n\nThere are a few differences from the ``register`` view:\n\n#. The user is queried first and stored in a variable for later use.\n\n :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.\n If the query returned no results, it returns ``None``. Later,\n :meth:`~sqlite3.Cursor.fetchall` will be used, which returns a list\n of all results.\n\n#. :func:`~werkzeug.security.check_password_hash` hashes the submitted\n password in the same way as the stored hash and securely compares\n them. If they match, the password is valid.\n\n#. :data:`session` is a :class:`dict` that stores data across requests.\n When validation succeeds, the user's ``id`` is stored in a new\n session. The data is stored in a *cookie* that is sent to the\n browser, and the browser then sends it back with subsequent requests.\n Flask securely *signs* the data so that it can't be tampered with.\n\nNow that the user's ``id`` is stored in the :data:`session`, it will be\navailable on subsequent requests. At the beginning of each request, if\na user is logged in their information should be loaded and made\navailable to other views.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.before_app_request\n def load_logged_in_user():\n user_id = session.get('user_id')\n\n if user_id is None:\n g.user = None\n else:\n g.user = get_db().execute(\n 'SELECT * FROM user WHERE id = ?', (user_id,)\n ).fetchone()\n\n:meth:`bp.before_app_request() ` registers\na function that runs before the view function, no matter what URL is\nrequested. ``load_logged_in_user`` checks if a user id is stored in the\n:data:`session` and gets that user's data from the database, storing it\non :data:`g.user `, which lasts for the length of the request. If\nthere is no user id, or if the id doesn't exist, ``g.user`` will be\n``None``.\n\n\nLogout\n------\n\nTo log out, you need to remove the user id from the :data:`session`.\nThen ``load_logged_in_user`` won't load a user on subsequent requests.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n @bp.route('/logout')\n def logout():\n session.clear()\n return redirect(url_for('index'))\n\n\nRequire Authentication in Other Views\n-------------------------------------\n\nCreating, editing, and deleting blog posts will require a user to be\nlogged in. A *decorator* can be used to check this for each view it's\napplied to.\n\n.. code-block:: python\n :caption: ``flaskr/auth.py``\n\n def login_required(view):\n @functools.wraps(view)\n def wrapped_view(**kwargs):\n if g.user is None:\n return redirect(url_for('auth.login'))\n\n return view(**kwargs)\n\n return wrapped_view\n\nThis decorator returns a new view function that wraps the original view\nit's applied to. The new function checks if a user is loaded and\nredirects to the login page otherwise. If a user is loaded the original\nview is called and continues normally. You'll use this decorator when\nwriting the blog views.\n\nEndpoints and URLs\n------------------\n\nThe :func:`url_for` function generates the URL to a view based on a name\nand arguments. The name associated with a view is also called the\n*endpoint*, and by default it's the same as the name of the view\nfunction.\n\nFor example, the ``hello()`` view that was added to the app\nfactory earlier in the tutorial has the name ``'hello'`` and can be\nlinked to with ``url_for('hello')``. If it took an argument, which\nyou'll see later, it would be linked to using\n``url_for('hello', who='World')``.\n\nWhen using a blueprint, the name of the blueprint is prepended to the\nname of the function, so the endpoint for the ``login`` function you\nwrote above is ``'auth.login'`` because you added it to the ``'auth'``\nblueprint.\n\nContinue to :doc:`templates`.\n"},{"id":355,"name":"xhr.html","nodeType":"TextFile","path":"examples/javascript/js_example/templates","text":"{% extends 'base.html' %}\n\n{% block intro %}\n XMLHttpRequest\n is the original JavaScript way to make requests. It's natively supported\n by all browsers, but has been superseded by\n fetch.\n{% endblock %}\n\n{% block script %}\n \n{% endblock %}\n"},{"col":4,"comment":"null","endLoc":194,"header":"def __new__(\n cls,\n days: float = ...,\n seconds: float = ...,\n microseconds: float = ...,\n milliseconds: float = ...,\n minutes: float = ...,\n hours: float = ...,\n weeks: float = ...,\n ) -> Self","id":356,"name":"__new__","nodeType":"Function","startLoc":185,"text":"def __new__(\n cls,\n days: float = ...,\n seconds: float = ...,\n microseconds: float = ...,\n milliseconds: float = ...,\n minutes: float = ...,\n hours: float = ...,\n weeks: float = ...,\n ) -> Self: ..."},{"col":4,"comment":"null","endLoc":196,"header":"@property\n def days(self) -> int","id":357,"name":"days","nodeType":"Function","startLoc":195,"text":"@property\n def days(self) -> int: ..."},{"col":4,"comment":"null","endLoc":198,"header":"@property\n def seconds(self) -> int","id":358,"name":"seconds","nodeType":"Function","startLoc":197,"text":"@property\n def seconds(self) -> int: ..."},{"col":4,"comment":"null","endLoc":200,"header":"@property\n def microseconds(self) -> int","id":359,"name":"microseconds","nodeType":"Function","startLoc":199,"text":"@property\n def microseconds(self) -> int: ..."},{"col":4,"comment":"null","endLoc":201,"header":"def total_seconds(self) -> float","id":360,"name":"total_seconds","nodeType":"Function","startLoc":201,"text":"def total_seconds(self) -> float: ..."},{"col":4,"comment":"null","endLoc":202,"header":"def __add__(self, __value: timedelta) -> timedelta","id":361,"name":"__add__","nodeType":"Function","startLoc":202,"text":"def __add__(self, __value: timedelta) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":203,"header":"def __radd__(self, __value: timedelta) -> timedelta","id":362,"name":"__radd__","nodeType":"Function","startLoc":203,"text":"def __radd__(self, __value: timedelta) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":204,"header":"def __sub__(self, __value: timedelta) -> timedelta","id":363,"name":"__sub__","nodeType":"Function","startLoc":204,"text":"def __sub__(self, __value: timedelta) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":54,"header":"def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self","id":364,"name":"__new__","nodeType":"Function","startLoc":54,"text":"def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ..."},{"col":4,"comment":"null","endLoc":205,"header":"def __rsub__(self, __value: timedelta) -> timedelta","id":365,"name":"__rsub__","nodeType":"Function","startLoc":205,"text":"def __rsub__(self, __value: timedelta) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":56,"header":"@classmethod\n def fromtimestamp(cls, __timestamp: float) -> Self","id":366,"name":"fromtimestamp","nodeType":"Function","startLoc":55,"text":"@classmethod\n def fromtimestamp(cls, __timestamp: float) -> Self: ..."},{"col":4,"comment":"null","endLoc":206,"header":"def __neg__(self) -> timedelta","id":367,"name":"__neg__","nodeType":"Function","startLoc":206,"text":"def __neg__(self) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":207,"header":"def __pos__(self) -> timedelta","id":368,"name":"__pos__","nodeType":"Function","startLoc":207,"text":"def __pos__(self) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":58,"header":"@classmethod\n def today(cls) -> Self","id":369,"name":"today","nodeType":"Function","startLoc":57,"text":"@classmethod\n def today(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":208,"header":"def __abs__(self) -> timedelta","id":370,"name":"__abs__","nodeType":"Function","startLoc":208,"text":"def __abs__(self) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":60,"header":"@classmethod\n def fromordinal(cls, __n: int) -> Self","id":371,"name":"fromordinal","nodeType":"Function","startLoc":59,"text":"@classmethod\n def fromordinal(cls, __n: int) -> Self: ..."},{"col":4,"comment":"null","endLoc":209,"header":"def __mul__(self, __value: float) -> timedelta","id":372,"name":"__mul__","nodeType":"Function","startLoc":209,"text":"def __mul__(self, __value: float) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":62,"header":"@classmethod\n def fromisoformat(cls, __date_string: str) -> Self","id":373,"name":"fromisoformat","nodeType":"Function","startLoc":61,"text":"@classmethod\n def fromisoformat(cls, __date_string: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":210,"header":"def __rmul__(self, __value: float) -> timedelta","id":374,"name":"__rmul__","nodeType":"Function","startLoc":210,"text":"def __rmul__(self, __value: float) -> timedelta: ..."},{"col":8,"comment":"null","endLoc":65,"header":"@classmethod\n def fromisocalendar(cls, year: int, week: int, day: int) -> Self","id":375,"name":"fromisocalendar","nodeType":"Function","startLoc":64,"text":"@classmethod\n def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ..."},{"col":4,"comment":"null","endLoc":212,"header":"@overload\n def __floordiv__(self, __value: timedelta) -> int","id":376,"name":"__floordiv__","nodeType":"Function","startLoc":211,"text":"@overload\n def __floordiv__(self, __value: timedelta) -> int: ..."},{"col":4,"comment":"null","endLoc":68,"header":"@property\n def year(self) -> int","id":377,"name":"year","nodeType":"Function","startLoc":67,"text":"@property\n def year(self) -> int: ..."},{"col":4,"comment":"null","endLoc":214,"header":"@overload\n def __floordiv__(self, __value: int) -> timedelta","id":378,"name":"__floordiv__","nodeType":"Function","startLoc":213,"text":"@overload\n def __floordiv__(self, __value: int) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":70,"header":"@property\n def month(self) -> int","id":379,"name":"month","nodeType":"Function","startLoc":69,"text":"@property\n def month(self) -> int: ..."},{"col":4,"comment":"null","endLoc":216,"header":"@overload\n def __truediv__(self, __value: timedelta) -> float","id":380,"name":"__truediv__","nodeType":"Function","startLoc":215,"text":"@overload\n def __truediv__(self, __value: timedelta) -> float: ..."},{"col":4,"comment":"null","endLoc":72,"header":"@property\n def day(self) -> int","id":381,"name":"day","nodeType":"Function","startLoc":71,"text":"@property\n def day(self) -> int: ..."},{"col":4,"comment":"null","endLoc":218,"header":"@overload\n def __truediv__(self, __value: float) -> timedelta","id":382,"name":"__truediv__","nodeType":"Function","startLoc":217,"text":"@overload\n def __truediv__(self, __value: float) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":73,"header":"def ctime(self) -> str","id":383,"name":"ctime","nodeType":"Function","startLoc":73,"text":"def ctime(self) -> str: ..."},{"col":4,"comment":"null","endLoc":219,"header":"def __mod__(self, __value: timedelta) -> timedelta","id":384,"name":"__mod__","nodeType":"Function","startLoc":219,"text":"def __mod__(self, __value: timedelta) -> timedelta: ..."},{"col":8,"comment":"null","endLoc":78,"header":"def strftime(self, format: str) -> str","id":385,"name":"strftime","nodeType":"Function","startLoc":78,"text":"def strftime(self, format: str) -> str: ..."},{"col":4,"comment":"null","endLoc":220,"header":"def __divmod__(self, __value: timedelta) -> tuple[int, timedelta]","id":386,"name":"__divmod__","nodeType":"Function","startLoc":220,"text":"def __divmod__(self, __value: timedelta) -> tuple[int, timedelta]: ..."},{"col":8,"comment":"null","endLoc":80,"header":"def strftime(self, __format: str) -> str","id":387,"name":"strftime","nodeType":"Function","startLoc":80,"text":"def strftime(self, __format: str) -> str: ..."},{"col":4,"comment":"null","endLoc":221,"header":"def __le__(self, __value: timedelta) -> bool","id":388,"name":"__le__","nodeType":"Function","startLoc":221,"text":"def __le__(self, __value: timedelta) -> bool: ..."},{"col":4,"comment":"null","endLoc":82,"header":"def __format__(self, __fmt: str) -> str","id":389,"name":"__format__","nodeType":"Function","startLoc":82,"text":"def __format__(self, __fmt: str) -> str: ..."},{"col":4,"comment":"null","endLoc":222,"header":"def __lt__(self, __value: timedelta) -> bool","id":390,"name":"__lt__","nodeType":"Function","startLoc":222,"text":"def __lt__(self, __value: timedelta) -> bool: ..."},{"col":4,"comment":"null","endLoc":83,"header":"def isoformat(self) -> str","id":391,"name":"isoformat","nodeType":"Function","startLoc":83,"text":"def isoformat(self) -> str: ..."},{"col":4,"comment":"null","endLoc":223,"header":"def __ge__(self, __value: timedelta) -> bool","id":392,"name":"__ge__","nodeType":"Function","startLoc":223,"text":"def __ge__(self, __value: timedelta) -> bool: ..."},{"col":4,"comment":"null","endLoc":84,"header":"def timetuple(self) -> struct_time","id":393,"name":"timetuple","nodeType":"Function","startLoc":84,"text":"def timetuple(self) -> struct_time: ..."},{"col":4,"comment":"null","endLoc":224,"header":"def __gt__(self, __value: timedelta) -> bool","id":394,"name":"__gt__","nodeType":"Function","startLoc":224,"text":"def __gt__(self, __value: timedelta) -> bool: ..."},{"col":4,"comment":"null","endLoc":85,"header":"def toordinal(self) -> int","id":395,"name":"toordinal","nodeType":"Function","startLoc":85,"text":"def toordinal(self) -> int: ..."},{"col":4,"comment":"null","endLoc":225,"header":"def __eq__(self, __value: object) -> bool","id":396,"name":"__eq__","nodeType":"Function","startLoc":225,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":86,"header":"def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self","id":397,"name":"replace","nodeType":"Function","startLoc":86,"text":"def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":226,"header":"def __bool__(self) -> bool","id":398,"name":"__bool__","nodeType":"Function","startLoc":226,"text":"def __bool__(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":87,"header":"def __le__(self, __value: date) -> bool","id":399,"name":"__le__","nodeType":"Function","startLoc":87,"text":"def __le__(self, __value: date) -> bool: ..."},{"col":4,"comment":"null","endLoc":227,"header":"def __hash__(self) -> int","id":400,"name":"__hash__","nodeType":"Function","startLoc":227,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":88,"header":"def __lt__(self, __value: date) -> bool","id":401,"name":"__lt__","nodeType":"Function","startLoc":88,"text":"def __lt__(self, __value: date) -> bool: ..."},{"col":4,"comment":"null","endLoc":89,"header":"def __ge__(self, __value: date) -> bool","id":402,"name":"__ge__","nodeType":"Function","startLoc":89,"text":"def __ge__(self, __value: date) -> bool: ..."},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":182,"id":403,"name":"min","nodeType":"Attribute","startLoc":182,"text":"min"},{"col":4,"comment":"null","endLoc":90,"header":"def __gt__(self, __value: date) -> bool","id":404,"name":"__gt__","nodeType":"Function","startLoc":90,"text":"def __gt__(self, __value: date) -> bool: ..."},{"col":4,"comment":"null","endLoc":91,"header":"def __eq__(self, __value: object) -> bool","id":405,"name":"__eq__","nodeType":"Function","startLoc":91,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":8,"comment":"null","endLoc":93,"header":"def __add__(self, __value: timedelta) -> Self","id":406,"name":"__add__","nodeType":"Function","startLoc":93,"text":"def __add__(self, __value: timedelta) -> Self: ..."},{"col":8,"comment":"null","endLoc":103,"header":"def __add__(self, __value: timedelta) -> date","id":407,"name":"__add__","nodeType":"Function","startLoc":103,"text":"def __add__(self, __value: timedelta) -> date: ..."},{"col":8,"comment":"null","endLoc":94,"header":"def __radd__(self, __value: timedelta) -> Self","id":408,"name":"__radd__","nodeType":"Function","startLoc":94,"text":"def __radd__(self, __value: timedelta) -> Self: ..."},{"col":8,"comment":"null","endLoc":104,"header":"def __radd__(self, __value: timedelta) -> date","id":409,"name":"__radd__","nodeType":"Function","startLoc":104,"text":"def __radd__(self, __value: timedelta) -> date: ..."},{"col":8,"comment":"null","endLoc":96,"header":"@overload\n def __sub__(self, __value: timedelta) -> Self","id":410,"name":"__sub__","nodeType":"Function","startLoc":95,"text":"@overload\n def __sub__(self, __value: timedelta) -> Self: ..."},{"col":8,"comment":"null","endLoc":98,"header":"@overload\n def __sub__(self, __value: datetime) -> NoReturn","id":411,"name":"__sub__","nodeType":"Function","startLoc":97,"text":"@overload\n def __sub__(self, __value: datetime) -> NoReturn: ..."},{"col":8,"comment":"null","endLoc":100,"header":"@overload\n def __sub__(self: _D, __value: _D) -> timedelta","id":412,"name":"__sub__","nodeType":"Function","startLoc":99,"text":"@overload\n def __sub__(self: _D, __value: _D) -> timedelta: ..."},{"col":8,"comment":"null","endLoc":106,"header":"@overload\n def __sub__(self, __value: timedelta) -> date","id":413,"name":"__sub__","nodeType":"Function","startLoc":105,"text":"@overload\n def __sub__(self, __value: timedelta) -> date: ..."},{"col":8,"comment":"null","endLoc":108,"header":"@overload\n def __sub__(self, __value: datetime) -> NoReturn","id":414,"name":"__sub__","nodeType":"Function","startLoc":107,"text":"@overload\n def __sub__(self, __value: datetime) -> NoReturn: ..."},{"col":8,"comment":"null","endLoc":110,"header":"@overload\n def __sub__(self, __value: date) -> timedelta","id":415,"name":"__sub__","nodeType":"Function","startLoc":109,"text":"@overload\n def __sub__(self, __value: date) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":112,"header":"def __hash__(self) -> int","id":416,"name":"__hash__","nodeType":"Function","startLoc":112,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":113,"header":"def weekday(self) -> int","id":417,"name":"weekday","nodeType":"Function","startLoc":113,"text":"def weekday(self) -> int: ..."},{"col":4,"comment":"null","endLoc":114,"header":"def isoweekday(self) -> int","id":418,"name":"isoweekday","nodeType":"Function","startLoc":114,"text":"def isoweekday(self) -> int: ..."},{"col":8,"comment":"null","endLoc":116,"header":"def isocalendar(self) -> _IsoCalendarDate","id":419,"name":"isocalendar","nodeType":"Function","startLoc":116,"text":"def isocalendar(self) -> _IsoCalendarDate: ..."},{"col":8,"comment":"null","endLoc":118,"header":"def isocalendar(self) -> tuple[int, int, int]","id":420,"name":"isocalendar","nodeType":"Function","startLoc":118,"text":"def isocalendar(self) -> tuple[int, int, int]: ..."},{"attributeType":"date","col":4,"comment":"null","endLoc":51,"id":421,"name":"min","nodeType":"Attribute","startLoc":51,"text":"min"},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":183,"id":422,"name":"max","nodeType":"Attribute","startLoc":183,"text":"max"},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":184,"id":423,"name":"resolution","nodeType":"Attribute","startLoc":184,"text":"resolution"},{"attributeType":"date","col":4,"comment":"null","endLoc":52,"id":424,"name":"max","nodeType":"Attribute","startLoc":52,"text":"max"},{"col":4,"comment":"null","endLoc":106,"header":"def update_wrapper(\n wrapper: Callable[_PWrapper, _RWrapper],\n wrapped: Callable[_PWrapped, _RWrapped],\n assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\", \"__type_params__\"),\n updated","id":425,"name":"update_wrapper","nodeType":"Function","startLoc":101,"text":"def update_wrapper(\n wrapper: Callable[_PWrapper, _RWrapper],\n wrapped: Callable[_PWrapped, _RWrapped],\n assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\", \"__type_params__\"),\n updated: Sequence[str] = (\"__dict__\",),\n ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ..."},{"attributeType":"timedelta","col":4,"comment":"null","endLoc":53,"id":426,"name":"resolution","nodeType":"Attribute","startLoc":53,"text":"resolution"},{"fileName":"debughelpers.py","filePath":"src/flask","id":427,"nodeType":"File","text":"import typing as t\n\nfrom .app import Flask\nfrom .blueprints import Blueprint\nfrom .globals import request_ctx\n\n\nclass UnexpectedUnicodeError(AssertionError, UnicodeError):\n \"\"\"Raised in places where we want some better error reporting for\n unexpected unicode or binary data.\n \"\"\"\n\n\nclass DebugFilesKeyError(KeyError, AssertionError):\n \"\"\"Raised from request.files during debugging. The idea is that it can\n provide a better error message than just a generic KeyError/BadRequest.\n \"\"\"\n\n def __init__(self, request, key):\n form_matches = request.form.getlist(key)\n buf = [\n f\"You tried to access the file {key!r} in the request.files\"\n \" dictionary but it does not exist. The mimetype for the\"\n f\" request is {request.mimetype!r} instead of\"\n \" 'multipart/form-data' which means that no file contents\"\n \" were transmitted. To fix this error you should provide\"\n ' enctype=\"multipart/form-data\" in your form.'\n ]\n if form_matches:\n names = \", \".join(repr(x) for x in form_matches)\n buf.append(\n \"\\n\\nThe browser instead transmitted some file names. \"\n f\"This was submitted: {names}\"\n )\n self.msg = \"\".join(buf)\n\n def __str__(self):\n return self.msg\n\n\nclass FormDataRoutingRedirect(AssertionError):\n \"\"\"This exception is raised in debug mode if a routing redirect\n would cause the browser to drop the method or body. This happens\n when method is not GET, HEAD or OPTIONS and the status code is not\n 307 or 308.\n \"\"\"\n\n def __init__(self, request):\n exc = request.routing_exception\n buf = [\n f\"A request was sent to '{request.url}', but routing issued\"\n f\" a redirect to the canonical URL '{exc.new_url}'.\"\n ]\n\n if f\"{request.base_url}/\" == exc.new_url.partition(\"?\")[0]:\n buf.append(\n \" The URL was defined with a trailing slash. Flask\"\n \" will redirect to the URL with a trailing slash if it\"\n \" was accessed without one.\"\n )\n\n buf.append(\n \" Send requests to the canonical URL, or use 307 or 308 for\"\n \" routing redirects. Otherwise, browsers will drop form\"\n \" data.\\n\\n\"\n \"This exception is only raised in debug mode.\"\n )\n super().__init__(\"\".join(buf))\n\n\ndef attach_enctype_error_multidict(request):\n \"\"\"Patch ``request.files.__getitem__`` to raise a descriptive error\n about ``enctype=multipart/form-data``.\n\n :param request: The request to patch.\n :meta private:\n \"\"\"\n oldcls = request.files.__class__\n\n class newcls(oldcls):\n def __getitem__(self, key):\n try:\n return super().__getitem__(key)\n except KeyError as e:\n if key not in request.form:\n raise\n\n raise DebugFilesKeyError(request, key).with_traceback(\n e.__traceback__\n ) from None\n\n newcls.__name__ = oldcls.__name__\n newcls.__module__ = oldcls.__module__\n request.files.__class__ = newcls\n\n\ndef _dump_loader_info(loader) -> t.Generator:\n yield f\"class: {type(loader).__module__}.{type(loader).__name__}\"\n for key, value in sorted(loader.__dict__.items()):\n if key.startswith(\"_\"):\n continue\n if isinstance(value, (tuple, list)):\n if not all(isinstance(x, str) for x in value):\n continue\n yield f\"{key}:\"\n for item in value:\n yield f\" - {item}\"\n continue\n elif not isinstance(value, (str, int, float, bool)):\n continue\n yield f\"{key}: {value!r}\"\n\n\ndef explain_template_loading_attempts(app: Flask, template, attempts) -> None:\n \"\"\"This should help developers understand what failed\"\"\"\n info = [f\"Locating template {template!r}:\"]\n total_found = 0\n blueprint = None\n if request_ctx and request_ctx.request.blueprint is not None:\n blueprint = request_ctx.request.blueprint\n\n for idx, (loader, srcobj, triple) in enumerate(attempts):\n if isinstance(srcobj, Flask):\n src_info = f\"application {srcobj.import_name!r}\"\n elif isinstance(srcobj, Blueprint):\n src_info = f\"blueprint {srcobj.name!r} ({srcobj.import_name})\"\n else:\n src_info = repr(srcobj)\n\n info.append(f\"{idx + 1:5}: trying loader of {src_info}\")\n\n for line in _dump_loader_info(loader):\n info.append(f\" {line}\")\n\n if triple is None:\n detail = \"no match\"\n else:\n detail = f\"found ({triple[1] or ''!r})\"\n total_found += 1\n info.append(f\" -> {detail}\")\n\n seems_fishy = False\n if total_found == 0:\n info.append(\"Error: the template could not be found.\")\n seems_fishy = True\n elif total_found > 1:\n info.append(\"Warning: multiple loaders returned a match for the template.\")\n seems_fishy = True\n\n if blueprint is not None and seems_fishy:\n info.append(\n \" The template was looked up from an endpoint that belongs\"\n f\" to the blueprint {blueprint!r}.\"\n )\n info.append(\" Maybe you did not place a template in the right folder?\")\n info.append(\" See https://flask.palletsprojects.com/blueprints/#templates\")\n\n app.logger.info(\"\\n\".join(info))\n"},{"col":4,"comment":"null","endLoc":119,"header":"def update_wrapper(\n wrapper: Callable[_PWrapper, _RWrapper],\n wrapped: Callable[_PWrapped, _RWrapped],\n assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n updated","id":429,"name":"update_wrapper","nodeType":"Function","startLoc":114,"text":"def update_wrapper(\n wrapper: Callable[_PWrapper, _RWrapper],\n wrapped: Callable[_PWrapped, _RWrapped],\n assigned: Sequence[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n updated: Sequence[str] = (\"__dict__\",),\n ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ..."},{"className":"Blueprint","col":0,"comment":"Represents a blueprint, a collection of routes and other\n app-related functions that can be registered on a real application\n later.\n\n A blueprint is an object that allows defining application functions\n without requiring an application object ahead of time. It uses the\n same decorators as :class:`~flask.Flask`, but defers the need for an\n application by recording them for later registration.\n\n Decorating a function with a blueprint creates a deferred function\n that is called with :class:`~flask.blueprints.BlueprintSetupState`\n when the blueprint is registered on an application.\n\n See :doc:`/blueprints` for more information.\n\n :param name: The name of the blueprint. Will be prepended to each\n endpoint name.\n :param import_name: The name of the blueprint package, usually\n ``__name__``. This helps locate the ``root_path`` for the\n blueprint.\n :param static_folder: A folder with static files that should be\n served by the blueprint's static route. The path is relative to\n the blueprint's root path. Blueprint static files are disabled\n by default.\n :param static_url_path: The url to serve static files from.\n Defaults to ``static_folder``. If the blueprint does not have\n a ``url_prefix``, the app's static route will take precedence,\n and the blueprint's static files won't be accessible.\n :param template_folder: A folder with templates that should be added\n to the app's template search path. The path is relative to the\n blueprint's root path. Blueprint templates are disabled by\n default. Blueprint templates have a lower precedence than those\n in the app's templates folder.\n :param url_prefix: A path to prepend to all of the blueprint's URLs,\n to make them distinct from the rest of the app's routes.\n :param subdomain: A subdomain that blueprint routes will match on by\n default.\n :param url_defaults: A dict of default values that blueprint routes\n will receive by default.\n :param root_path: By default, the blueprint will automatically set\n this based on ``import_name``. In certain situations this\n automatic detection can fail, so the path can be specified\n manually instead.\n\n .. versionchanged:: 1.1.0\n Blueprints have a ``cli`` group to register nested CLI commands.\n The ``cli_group`` parameter controls the name of the group under\n the ``flask`` command.\n\n .. versionadded:: 0.7\n ","endLoc":624,"id":430,"nodeType":"Class","startLoc":117,"text":"class Blueprint(Scaffold):\n \"\"\"Represents a blueprint, a collection of routes and other\n app-related functions that can be registered on a real application\n later.\n\n A blueprint is an object that allows defining application functions\n without requiring an application object ahead of time. It uses the\n same decorators as :class:`~flask.Flask`, but defers the need for an\n application by recording them for later registration.\n\n Decorating a function with a blueprint creates a deferred function\n that is called with :class:`~flask.blueprints.BlueprintSetupState`\n when the blueprint is registered on an application.\n\n See :doc:`/blueprints` for more information.\n\n :param name: The name of the blueprint. Will be prepended to each\n endpoint name.\n :param import_name: The name of the blueprint package, usually\n ``__name__``. This helps locate the ``root_path`` for the\n blueprint.\n :param static_folder: A folder with static files that should be\n served by the blueprint's static route. The path is relative to\n the blueprint's root path. Blueprint static files are disabled\n by default.\n :param static_url_path: The url to serve static files from.\n Defaults to ``static_folder``. If the blueprint does not have\n a ``url_prefix``, the app's static route will take precedence,\n and the blueprint's static files won't be accessible.\n :param template_folder: A folder with templates that should be added\n to the app's template search path. The path is relative to the\n blueprint's root path. Blueprint templates are disabled by\n default. Blueprint templates have a lower precedence than those\n in the app's templates folder.\n :param url_prefix: A path to prepend to all of the blueprint's URLs,\n to make them distinct from the rest of the app's routes.\n :param subdomain: A subdomain that blueprint routes will match on by\n default.\n :param url_defaults: A dict of default values that blueprint routes\n will receive by default.\n :param root_path: By default, the blueprint will automatically set\n this based on ``import_name``. In certain situations this\n automatic detection can fail, so the path can be specified\n manually instead.\n\n .. versionchanged:: 1.1.0\n Blueprints have a ``cli`` group to register nested CLI commands.\n The ``cli_group`` parameter controls the name of the group under\n the ``flask`` command.\n\n .. versionadded:: 0.7\n \"\"\"\n\n _got_registered_once = False\n\n def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n url_prefix: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_defaults: t.Optional[dict] = None,\n root_path: t.Optional[str] = None,\n cli_group: t.Optional[str] = _sentinel, # type: ignore\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n\n if not name:\n raise ValueError(\"'name' may not be empty.\")\n\n if \".\" in name:\n raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n self.name = name\n self.url_prefix = url_prefix\n self.subdomain = subdomain\n self.deferred_functions: t.List[DeferredSetupFunction] = []\n\n if url_defaults is None:\n url_defaults = {}\n\n self.url_values_defaults = url_defaults\n self.cli_group = cli_group\n self._blueprints: t.List[t.Tuple[\"Blueprint\", dict]] = []\n\n def _check_setup_finished(self, f_name: str) -> None:\n if self._got_registered_once:\n raise AssertionError(\n f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n f\" '{self.name}'. It has already been registered at least once, any\"\n \" changes will not be applied consistently.\\n\"\n \"Make sure all imports, decorators, functions, etc. needed to set up\"\n \" the blueprint are done before registering it.\"\n )\n\n @setupmethod\n def record(self, func: t.Callable) -> None:\n \"\"\"Registers a function that is called when the blueprint is\n registered on the application. This function is called with the\n state as argument as returned by the :meth:`make_setup_state`\n method.\n \"\"\"\n self.deferred_functions.append(func)\n\n @setupmethod\n def record_once(self, func: t.Callable) -> None:\n \"\"\"Works like :meth:`record` but wraps the function in another\n function that will ensure the function is only called once. If the\n blueprint is registered a second time on the application, the\n function passed is not called.\n \"\"\"\n\n def wrapper(state: BlueprintSetupState) -> None:\n if state.first_registration:\n func(state)\n\n self.record(update_wrapper(wrapper, func))\n\n def make_setup_state(\n self, app: \"Flask\", options: dict, first_registration: bool = False\n ) -> BlueprintSetupState:\n \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n object that is later passed to the register callback functions.\n Subclasses can override this to return a subclass of the setup state.\n \"\"\"\n return BlueprintSetupState(self, app, options, first_registration)\n\n @setupmethod\n def register_blueprint(self, blueprint: \"Blueprint\", **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n arguments passed to this method will override the defaults set\n on the blueprint.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with unique names\n for ``url_for``.\n\n .. versionadded:: 2.0\n \"\"\"\n if blueprint is self:\n raise ValueError(\"Cannot register a blueprint on itself\")\n self._blueprints.append((blueprint, options))\n\n def register(self, app: \"Flask\", options: dict) -> None:\n \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n views and callbacks registered on the blueprint with the\n application. Creates a :class:`.BlueprintSetupState` and calls\n each :meth:`record` callback with it.\n\n :param app: The application this blueprint is being registered\n with.\n :param options: Keyword arguments forwarded from\n :meth:`~Flask.register_blueprint`.\n\n .. versionchanged:: 2.3\n Nested blueprints now correctly apply subdomains.\n\n .. versionchanged:: 2.1\n Registering the same blueprint with the same name multiple\n times is an error.\n\n .. versionchanged:: 2.0.1\n Nested blueprints are registered with their dotted name.\n This allows different blueprints with the same name to be\n nested at different locations.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with unique names\n for ``url_for``.\n \"\"\"\n name_prefix = options.get(\"name_prefix\", \"\")\n self_name = options.get(\"name\", self.name)\n name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n if name in app.blueprints:\n bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n raise ValueError(\n f\"The name '{self_name}' is already registered for\"\n f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n f\" provide a unique name.\"\n )\n\n first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n first_name_registration = name not in app.blueprints\n\n app.blueprints[name] = self\n self._got_registered_once = True\n state = self.make_setup_state(app, options, first_bp_registration)\n\n if self.has_static_folder:\n state.add_url_rule(\n f\"{self.static_url_path}/\",\n view_func=self.send_static_file,\n endpoint=\"static\",\n )\n\n # Merge blueprint data into parent.\n if first_bp_registration or first_name_registration:\n\n def extend(bp_dict, parent_dict):\n for key, values in bp_dict.items():\n key = name if key is None else f\"{name}.{key}\"\n parent_dict[key].extend(values)\n\n for key, value in self.error_handler_spec.items():\n key = name if key is None else f\"{name}.{key}\"\n value = defaultdict(\n dict,\n {\n code: {\n exc_class: func for exc_class, func in code_values.items()\n }\n for code, code_values in value.items()\n },\n )\n app.error_handler_spec[key] = value\n\n for endpoint, func in self.view_functions.items():\n app.view_functions[endpoint] = func\n\n extend(self.before_request_funcs, app.before_request_funcs)\n extend(self.after_request_funcs, app.after_request_funcs)\n extend(\n self.teardown_request_funcs,\n app.teardown_request_funcs,\n )\n extend(self.url_default_functions, app.url_default_functions)\n extend(self.url_value_preprocessors, app.url_value_preprocessors)\n extend(self.template_context_processors, app.template_context_processors)\n\n for deferred in self.deferred_functions:\n deferred(state)\n\n cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n if self.cli.commands:\n if cli_resolved_group is None:\n app.cli.commands.update(self.cli.commands)\n elif cli_resolved_group is _sentinel:\n self.cli.name = name\n app.cli.add_command(self.cli)\n else:\n self.cli.name = cli_resolved_group\n app.cli.add_command(self.cli)\n\n for blueprint, bp_options in self._blueprints:\n bp_options = bp_options.copy()\n bp_url_prefix = bp_options.get(\"url_prefix\")\n bp_subdomain = bp_options.get(\"subdomain\")\n\n if bp_subdomain is None:\n bp_subdomain = blueprint.subdomain\n\n if state.subdomain is not None and bp_subdomain is not None:\n bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n elif bp_subdomain is not None:\n bp_options[\"subdomain\"] = bp_subdomain\n elif state.subdomain is not None:\n bp_options[\"subdomain\"] = state.subdomain\n\n if bp_url_prefix is None:\n bp_url_prefix = blueprint.url_prefix\n\n if state.url_prefix is not None and bp_url_prefix is not None:\n bp_options[\"url_prefix\"] = (\n state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n )\n elif bp_url_prefix is not None:\n bp_options[\"url_prefix\"] = bp_url_prefix\n elif state.url_prefix is not None:\n bp_options[\"url_prefix\"] = state.url_prefix\n\n bp_options[\"name_prefix\"] = name\n blueprint.register(app, bp_options)\n\n @setupmethod\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[ft.RouteCallable] = None,\n provide_automatic_options: t.Optional[bool] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n full documentation.\n\n The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n used with :func:`url_for`, is prefixed with the blueprint's name.\n \"\"\"\n if endpoint and \".\" in endpoint:\n raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n self.record(\n lambda s: s.add_url_rule(\n rule,\n endpoint,\n view_func,\n provide_automatic_options=provide_automatic_options,\n **options,\n )\n )\n\n @setupmethod\n def app_template_filter(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_filter], T_template_filter]:\n \"\"\"Register a template filter, available in any template rendered by the\n application. Equivalent to :meth:`.Flask.template_filter`.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_filter) -> T_template_filter:\n self.add_app_template_filter(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_app_template_filter(\n self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a template filter, available in any template rendered by the\n application. Works like the :meth:`app_template_filter` decorator. Equivalent to\n :meth:`.Flask.add_template_filter`.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.filters[name or f.__name__] = f\n\n self.record_once(register_template)\n\n @setupmethod\n def app_template_test(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_test], T_template_test]:\n \"\"\"Register a template test, available in any template rendered by the\n application. Equivalent to :meth:`.Flask.template_test`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_test) -> T_template_test:\n self.add_app_template_test(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_app_template_test(\n self, f: ft.TemplateTestCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a template test, available in any template rendered by the\n application. Works like the :meth:`app_template_test` decorator. Equivalent to\n :meth:`.Flask.add_template_test`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.tests[name or f.__name__] = f\n\n self.record_once(register_template)\n\n @setupmethod\n def app_template_global(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_global], T_template_global]:\n \"\"\"Register a template global, available in any template rendered by the\n application. Equivalent to :meth:`.Flask.template_global`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_global) -> T_template_global:\n self.add_app_template_global(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_app_template_global(\n self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a template global, available in any template rendered by the\n application. Works like the :meth:`app_template_global` decorator. Equivalent to\n :meth:`.Flask.add_template_global`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.globals[name or f.__name__] = f\n\n self.record_once(register_template)\n\n @setupmethod\n def before_app_request(self, f: T_before_request) -> T_before_request:\n \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def after_app_request(self, f: T_after_request) -> T_after_request:\n \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def teardown_app_request(self, f: T_teardown) -> T_teardown:\n \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def app_context_processor(\n self, f: T_template_context_processor\n ) -> T_template_context_processor:\n \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n \"\"\"\n self.record_once(\n lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def app_errorhandler(\n self, code: t.Union[t.Type[Exception], int]\n ) -> t.Callable[[T_error_handler], T_error_handler]:\n \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n \"\"\"\n\n def decorator(f: T_error_handler) -> T_error_handler:\n self.record_once(lambda s: s.app.errorhandler(code)(f))\n return f\n\n return decorator\n\n @setupmethod\n def app_url_value_preprocessor(\n self, f: T_url_value_preprocessor\n ) -> T_url_value_preprocessor:\n \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n \"\"\"\n self.record_once(\n lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n \"\"\"\n self.record_once(\n lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n )\n return f"},{"col":4,"comment":"null","endLoc":131,"header":"@property\n def func(self) -> Callable[..., _T]","id":431,"name":"func","nodeType":"Function","startLoc":130,"text":"@property\n def func(self) -> Callable[..., _T]: ..."},{"col":4,"comment":"null","endLoc":133,"header":"@property\n def args(self) -> tuple[Any, ...]","id":433,"name":"args","nodeType":"Function","startLoc":132,"text":"@property\n def args(self) -> tuple[Any, ...]: ..."},{"col":4,"comment":"null","endLoc":135,"header":"@property\n def keywords(self) -> dict[str, Any]","id":434,"name":"keywords","nodeType":"Function","startLoc":134,"text":"@property\n def keywords(self) -> dict[str, Any]: ..."},{"col":4,"comment":"null","endLoc":136,"header":"def __new__(cls, __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self","id":435,"name":"__new__","nodeType":"Function","startLoc":136,"text":"def __new__(cls, __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self: ..."},{"col":4,"comment":"null","endLoc":137,"header":"def __call__(__self, *args: Any, **kwargs: Any) -> _T","id":436,"name":"__call__","nodeType":"Function","startLoc":137,"text":"def __call__(__self, *args: Any, **kwargs: Any) -> _T: ..."},{"col":8,"comment":"null","endLoc":139,"header":"def __class_getitem__(cls, item: Any) -> GenericAlias","id":437,"name":"__class_getitem__","nodeType":"Function","startLoc":139,"text":"def __class_getitem__(cls, item: Any) -> GenericAlias: ..."},{"className":"FileSystemLoader","col":0,"comment":"Loads templates from the file system. This loader can find templates\n in folders on the file system and is the preferred way to load them.\n\n The loader takes the path to the templates as string, or if multiple\n locations are wanted a list of them which is then looked up in the\n given order::\n\n >>> loader = FileSystemLoader('/path/to/templates')\n >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])\n\n Per default the template encoding is ``'utf-8'`` which can be changed\n by setting the `encoding` parameter to something else.\n\n To follow symbolic links, set the *followlinks* parameter to ``True``::\n\n >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)\n\n .. versionchanged:: 2.8\n The ``followlinks`` parameter was added.\n ","endLoc":214,"id":438,"nodeType":"Class","startLoc":141,"text":"class FileSystemLoader(BaseLoader):\n \"\"\"Loads templates from the file system. This loader can find templates\n in folders on the file system and is the preferred way to load them.\n\n The loader takes the path to the templates as string, or if multiple\n locations are wanted a list of them which is then looked up in the\n given order::\n\n >>> loader = FileSystemLoader('/path/to/templates')\n >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])\n\n Per default the template encoding is ``'utf-8'`` which can be changed\n by setting the `encoding` parameter to something else.\n\n To follow symbolic links, set the *followlinks* parameter to ``True``::\n\n >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)\n\n .. versionchanged:: 2.8\n The ``followlinks`` parameter was added.\n \"\"\"\n\n def __init__(self, searchpath, encoding=\"utf-8\", followlinks=False):\n if not isinstance(searchpath, abc.Iterable) or isinstance(\n searchpath, string_types\n ):\n searchpath = [searchpath]\n\n # In Python 3.5, os.path.join doesn't support Path. This can be\n # simplified to list(searchpath) when Python 3.5 is dropped.\n self.searchpath = [fspath(p) for p in searchpath]\n\n self.encoding = encoding\n self.followlinks = followlinks\n\n def get_source(self, environment, template):\n pieces = split_template_path(template)\n for searchpath in self.searchpath:\n filename = path.join(searchpath, *pieces)\n f = open_if_exists(filename)\n if f is None:\n continue\n try:\n contents = f.read().decode(self.encoding)\n finally:\n f.close()\n\n mtime = path.getmtime(filename)\n\n def uptodate():\n try:\n return path.getmtime(filename) == mtime\n except OSError:\n return False\n\n return contents, filename, uptodate\n raise TemplateNotFound(template)\n\n def list_templates(self):\n found = set()\n for searchpath in self.searchpath:\n walk_dir = os.walk(searchpath, followlinks=self.followlinks)\n for dirpath, _, filenames in walk_dir:\n for filename in filenames:\n template = (\n os.path.join(dirpath, filename)[len(searchpath) :]\n .strip(os.path.sep)\n .replace(os.path.sep, \"/\")\n )\n if template[:2] == \"./\":\n template = template[2:]\n if template not in found:\n found.add(template)\n return sorted(found)"},{"id":440,"name":"blog.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nBlog Blueprint\n==============\n\nYou'll use the same techniques you learned about when writing the\nauthentication blueprint to write the blog blueprint. The blog should\nlist all posts, allow logged in users to create posts, and allow the\nauthor of a post to edit or delete it.\n\nAs you implement each view, keep the development server running. As you\nsave your changes, try going to the URL in your browser and testing them\nout.\n\nThe Blueprint\n-------------\n\nDefine the blueprint and register it in the application factory.\n\n.. code-block:: python\n :caption: ``flaskr/blog.py``\n\n from flask import (\n Blueprint, flash, g, redirect, render_template, request, url_for\n )\n from werkzeug.exceptions import abort\n\n from flaskr.auth import login_required\n from flaskr.db import get_db\n\n bp = Blueprint('blog', __name__)\n\nImport and register the blueprint from the factory using\n:meth:`app.register_blueprint() `. Place the\nnew code at the end of the factory function before returning the app.\n\n.. code-block:: python\n :caption: ``flaskr/__init__.py``\n\n def create_app():\n app = ...\n # existing code omitted\n\n from . import blog\n app.register_blueprint(blog.bp)\n app.add_url_rule('/', endpoint='index')\n\n return app\n\n\nUnlike the auth blueprint, the blog blueprint does not have a\n``url_prefix``. So the ``index`` view will be at ``/``, the ``create``\nview at ``/create``, and so on. The blog is the main feature of Flaskr,\nso it makes sense that the blog index will be the main index.\n\nHowever, the endpoint for the ``index`` view defined below will be\n``blog.index``. Some of the authentication views referred to a plain\n``index`` endpoint. :meth:`app.add_url_rule() `\nassociates the endpoint name ``'index'`` with the ``/`` url so that\n``url_for('index')`` or ``url_for('blog.index')`` will both work,\ngenerating the same ``/`` URL either way.\n\nIn another application you might give the blog blueprint a\n``url_prefix`` and define a separate ``index`` view in the application\nfactory, similar to the ``hello`` view. Then the ``index`` and\n``blog.index`` endpoints and URLs would be different.\n\n\nIndex\n-----\n\nThe index will show all of the posts, most recent first. A ``JOIN`` is\nused so that the author information from the ``user`` table is\navailable in the result.\n\n.. code-block:: python\n :caption: ``flaskr/blog.py``\n\n @bp.route('/')\n def index():\n db = get_db()\n posts = db.execute(\n 'SELECT p.id, title, body, created, author_id, username'\n ' FROM post p JOIN user u ON p.author_id = u.id'\n ' ORDER BY created DESC'\n ).fetchall()\n return render_template('blog/index.html', posts=posts)\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/blog/index.html``\n\n {% extends 'base.html' %}\n\n {% block header %}\n

{% block title %}Posts{% endblock %}

\n {% if g.user %}\n New\n {% endif %}\n {% endblock %}\n\n {% block content %}\n {% for post in posts %}\n
\n
\n
\n

{{ post['title'] }}

\n
by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}
\n
\n {% if g.user['id'] == post['author_id'] %}\n Edit\n {% endif %}\n
\n

{{ post['body'] }}

\n
\n {% if not loop.last %}\n
\n {% endif %}\n {% endfor %}\n {% endblock %}\n\nWhen a user is logged in, the ``header`` block adds a link to the\n``create`` view. When the user is the author of a post, they'll see an\n\"Edit\" link to the ``update`` view for that post. ``loop.last`` is a\nspecial variable available inside `Jinja for loops`_. It's used to\ndisplay a line after each post except the last one, to visually separate\nthem.\n\n.. _Jinja for loops: https://jinja.palletsprojects.com/templates/#for\n\n\nCreate\n------\n\nThe ``create`` view works the same as the auth ``register`` view. Either\nthe form is displayed, or the posted data is validated and the post is\nadded to the database or an error is shown.\n\nThe ``login_required`` decorator you wrote earlier is used on the blog\nviews. A user must be logged in to visit these views, otherwise they\nwill be redirected to the login page.\n\n.. code-block:: python\n :caption: ``flaskr/blog.py``\n\n @bp.route('/create', methods=('GET', 'POST'))\n @login_required\n def create():\n if request.method == 'POST':\n title = request.form['title']\n body = request.form['body']\n error = None\n\n if not title:\n error = 'Title is required.'\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n 'INSERT INTO post (title, body, author_id)'\n ' VALUES (?, ?, ?)',\n (title, body, g.user['id'])\n )\n db.commit()\n return redirect(url_for('blog.index'))\n\n return render_template('blog/create.html')\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/blog/create.html``\n\n {% extends 'base.html' %}\n\n {% block header %}\n

{% block title %}New Post{% endblock %}

\n {% endblock %}\n\n {% block content %}\n
\n \n \n \n \n \n
\n {% endblock %}\n\n\nUpdate\n------\n\nBoth the ``update`` and ``delete`` views will need to fetch a ``post``\nby ``id`` and check if the author matches the logged in user. To avoid\nduplicating code, you can write a function to get the ``post`` and call\nit from each view.\n\n.. code-block:: python\n :caption: ``flaskr/blog.py``\n\n def get_post(id, check_author=True):\n post = get_db().execute(\n 'SELECT p.id, title, body, created, author_id, username'\n ' FROM post p JOIN user u ON p.author_id = u.id'\n ' WHERE p.id = ?',\n (id,)\n ).fetchone()\n\n if post is None:\n abort(404, f\"Post id {id} doesn't exist.\")\n\n if check_author and post['author_id'] != g.user['id']:\n abort(403)\n\n return post\n\n:func:`abort` will raise a special exception that returns an HTTP status\ncode. It takes an optional message to show with the error, otherwise a\ndefault message is used. ``404`` means \"Not Found\", and ``403`` means\n\"Forbidden\". (``401`` means \"Unauthorized\", but you redirect to the\nlogin page instead of returning that status.)\n\nThe ``check_author`` argument is defined so that the function can be\nused to get a ``post`` without checking the author. This would be useful\nif you wrote a view to show an individual post on a page, where the user\ndoesn't matter because they're not modifying the post.\n\n.. code-block:: python\n :caption: ``flaskr/blog.py``\n\n @bp.route('//update', methods=('GET', 'POST'))\n @login_required\n def update(id):\n post = get_post(id)\n\n if request.method == 'POST':\n title = request.form['title']\n body = request.form['body']\n error = None\n\n if not title:\n error = 'Title is required.'\n\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n 'UPDATE post SET title = ?, body = ?'\n ' WHERE id = ?',\n (title, body, id)\n )\n db.commit()\n return redirect(url_for('blog.index'))\n\n return render_template('blog/update.html', post=post)\n\nUnlike the views you've written so far, the ``update`` function takes\nan argument, ``id``. That corresponds to the ```` in the route.\nA real URL will look like ``/1/update``. Flask will capture the ``1``,\nensure it's an :class:`int`, and pass it as the ``id`` argument. If you\ndon't specify ``int:`` and instead do ````, it will be a string.\nTo generate a URL to the update page, :func:`url_for` needs to be passed\nthe ``id`` so it knows what to fill in:\n``url_for('blog.update', id=post['id'])``. This is also in the\n``index.html`` file above.\n\nThe ``create`` and ``update`` views look very similar. The main\ndifference is that the ``update`` view uses a ``post`` object and an\n``UPDATE`` query instead of an ``INSERT``. With some clever refactoring,\nyou could use one view and template for both actions, but for the\ntutorial it's clearer to keep them separate.\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/blog/update.html``\n\n {% extends 'base.html' %}\n\n {% block header %}\n

{% block title %}Edit \"{{ post['title'] }}\"{% endblock %}

\n {% endblock %}\n\n {% block content %}\n
\n \n \n \n \n \n
\n
\n
\n \n
\n {% endblock %}\n\nThis template has two forms. The first posts the edited data to the\ncurrent page (``//update``). The other form contains only a button\nand specifies an ``action`` attribute that posts to the delete view\ninstead. The button uses some JavaScript to show a confirmation dialog\nbefore submitting.\n\nThe pattern ``{{ request.form['title'] or post['title'] }}`` is used to\nchoose what data appears in the form. When the form hasn't been\nsubmitted, the original ``post`` data appears, but if invalid form data\nwas posted you want to display that so the user can fix the error, so\n``request.form`` is used instead. :data:`request` is another variable\nthat's automatically available in templates.\n\n\nDelete\n------\n\nThe delete view doesn't have its own template, the delete button is part\nof ``update.html`` and posts to the ``//delete`` URL. Since there\nis no template, it will only handle the ``POST`` method and then redirect\nto the ``index`` view.\n\n.. code-block:: python\n :caption: ``flaskr/blog.py``\n\n @bp.route('//delete', methods=('POST',))\n @login_required\n def delete(id):\n get_post(id)\n db = get_db()\n db.execute('DELETE FROM post WHERE id = ?', (id,))\n db.commit()\n return redirect(url_for('blog.index'))\n\nCongratulations, you've now finished writing your application! Take some\ntime to try out everything in the browser. However, there's still more\nto do before the project is complete.\n\nContinue to :doc:`install`.\n"},{"id":441,"name":".flake8","nodeType":"TextFile","path":"","text":"[flake8]\nextend-select =\n # bugbear\n B\n # bugbear opinions\n B9\n # implicit str concat\n ISC\nextend-ignore =\n # slice notation whitespace, invalid\n E203\n # line length, handled by bugbear B950\n E501\n # bare except, handled by bugbear B001\n E722\n # zip with strict=, requires python >= 3.10\n B905\n # string formatting opinion, B028 renamed to B907\n B028\n B907\n# up to 88 allowed by bugbear B950\nmax-line-length = 80\nper-file-ignores =\n # __init__ exports names\n src/flask/__init__.py: F401\n"},{"col":4,"comment":"null","endLoc":209,"header":"def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n url_prefix: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_defaults: t.Optional[dict] = None,\n root_path: t.Optional[str] = None,\n cli_group: t.Optional[str] = _sentinel, # type: ignore\n )","id":442,"name":"__init__","nodeType":"Function","startLoc":172,"text":"def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n url_prefix: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_defaults: t.Optional[dict] = None,\n root_path: t.Optional[str] = None,\n cli_group: t.Optional[str] = _sentinel, # type: ignore\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n\n if not name:\n raise ValueError(\"'name' may not be empty.\")\n\n if \".\" in name:\n raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n self.name = name\n self.url_prefix = url_prefix\n self.subdomain = subdomain\n self.deferred_functions: t.List[DeferredSetupFunction] = []\n\n if url_defaults is None:\n url_defaults = {}\n\n self.url_values_defaults = url_defaults\n self.cli_group = cli_group\n self._blueprints: t.List[t.Tuple[\"Blueprint\", dict]] = []"},{"id":443,"name":"examples/tutorial","nodeType":"Package"},{"id":444,"name":".gitignore","nodeType":"TextFile","path":"examples/tutorial","text":".venv/\n*.pyc\n__pycache__/\ninstance/\n.cache/\n.pytest_cache/\n.coverage\nhtmlcov/\ndist/\nbuild/\n*.egg-info/\n.idea/\n*.swp\n*~\n"},{"id":445,"name":"make.bat","nodeType":"TextFile","path":"docs","text":"@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-build\n)\nset SOURCEDIR=.\nset BUILDDIR=_build\n\nif \"%1\" == \"\" goto help\n\n%SPHINXBUILD% >NUL 2>NUL\nif errorlevel 9009 (\n\techo.\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\n\techo.installed, then set the SPHINXBUILD environment variable to point\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\n\techo.may add the Sphinx directory to PATH.\n\techo.\n\techo.If you don't have Sphinx installed, grab it from\n\techo.http://sphinx-doc.org/\n\texit /b 1\n)\n\n%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\ngoto end\n\n:help\n%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\n\n:end\npopd\n"},{"className":"Response","col":0,"comment":"The response object that is used by default in Flask. Works like the\n response object from Werkzeug but is set to have an HTML mimetype by\n default. Quite often you don't have to create this object yourself because\n :meth:`~flask.Flask.make_response` will take care of that for you.\n\n If you want to replace the response object used you can subclass this and\n set :attr:`~flask.Flask.response_class` to your subclass.\n\n .. versionchanged:: 1.0\n JSON support is added to the response, like the request. This is useful\n when testing to get the test client response data as JSON.\n\n .. versionchanged:: 1.0\n\n Added :attr:`max_cookie_size`.\n ","endLoc":171,"id":446,"nodeType":"Class","startLoc":136,"text":"class Response(ResponseBase):\n \"\"\"The response object that is used by default in Flask. Works like the\n response object from Werkzeug but is set to have an HTML mimetype by\n default. Quite often you don't have to create this object yourself because\n :meth:`~flask.Flask.make_response` will take care of that for you.\n\n If you want to replace the response object used you can subclass this and\n set :attr:`~flask.Flask.response_class` to your subclass.\n\n .. versionchanged:: 1.0\n JSON support is added to the response, like the request. This is useful\n when testing to get the test client response data as JSON.\n\n .. versionchanged:: 1.0\n\n Added :attr:`max_cookie_size`.\n \"\"\"\n\n default_mimetype: t.Optional[str] = \"text/html\"\n\n json_module = json\n\n autocorrect_location_header = False\n\n @property\n def max_cookie_size(self) -> int: # type: ignore\n \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n Werkzeug's docs.\n \"\"\"\n if current_app:\n return current_app.config[\"MAX_COOKIE_SIZE\"]\n\n # return Werkzeug's default when not in an app context\n return super().max_cookie_size"},{"id":447,"name":"tests/test_apps/blueprintapp/apps/frontend/templates/frontend","nodeType":"Package"},{"id":448,"name":"index.html","nodeType":"TextFile","path":"tests/test_apps/blueprintapp/apps/frontend/templates/frontend","text":"Hello from the Frontend\n"},{"col":4,"comment":"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n Werkzeug's docs.\n ","endLoc":171,"header":"@property\n def max_cookie_size(self) -> int","id":449,"name":"max_cookie_size","nodeType":"Function","startLoc":160,"text":"@property\n def max_cookie_size(self) -> int: # type: ignore\n \"\"\"Read-only view of the :data:`MAX_COOKIE_SIZE` config key.\n\n See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in\n Werkzeug's docs.\n \"\"\"\n if current_app:\n return current_app.config[\"MAX_COOKIE_SIZE\"]\n\n # return Werkzeug's default when not in an app context\n return super().max_cookie_size"},{"className":"Path","col":0,"comment":"null","endLoc":237,"id":450,"nodeType":"Class","startLoc":95,"text":"class Path(PurePath):\n def __new__(cls, *args: StrPath, **kwargs: Any) -> Self: ...\n def __enter__(self) -> Self: ...\n def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n @classmethod\n def cwd(cls) -> Self: ...\n if sys.version_info >= (3, 10):\n def stat(self, *, follow_symlinks: bool = True) -> stat_result: ...\n def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ...\n else:\n def stat(self) -> stat_result: ...\n def chmod(self, mode: int) -> None: ...\n\n if sys.version_info >= (3, 12):\n def exists(self, *, follow_symlinks: bool = True) -> bool: ...\n def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n else:\n def exists(self) -> bool: ...\n def glob(self, pattern: str) -> Generator[Self, None, None]: ...\n def rglob(self, pattern: str) -> Generator[Self, None, None]: ...\n\n def is_dir(self) -> bool: ...\n def is_file(self) -> bool: ...\n def is_symlink(self) -> bool: ...\n def is_socket(self) -> bool: ...\n def is_fifo(self) -> bool: ...\n def is_block_device(self) -> bool: ...\n def is_char_device(self) -> bool: ...\n if sys.version_info >= (3, 12):\n def is_junction(self) -> bool: ...\n\n def iterdir(self) -> Generator[Self, None, None]: ...\n def lchmod(self, mode: int) -> None: ...\n def lstat(self) -> stat_result: ...\n def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ...\n # Adapted from builtins.open\n # Text mode: always returns a TextIOWrapper\n # The Traversable .open in stdlib/importlib/abc.pyi should be kept in sync with this.\n @overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper: ...\n # Unbuffered binary mode: returns a FileIO\n @overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO: ...\n # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter\n @overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom: ...\n @overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter: ...\n @overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader: ...\n # Buffering cannot be determined: fall back to BinaryIO\n @overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO: ...\n # Fallback if mode is not specified\n @overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]: ...\n if sys.platform != \"win32\":\n # These methods do \"exist\" on Windows, but they always raise NotImplementedError,\n # so it's safer to pretend they don't exist\n def owner(self) -> str: ...\n def group(self) -> str: ...\n\n # This method does \"exist\" on Windows on <3.12, but always raises NotImplementedError\n # On py312+, it works properly on Windows, as with all other platforms\n if sys.platform != \"win32\" or sys.version_info >= (3, 12):\n def is_mount(self) -> bool: ...\n\n if sys.version_info >= (3, 9):\n def readlink(self) -> Self: ...\n if sys.version_info >= (3, 8):\n def rename(self, target: str | PurePath) -> Self: ...\n def replace(self, target: str | PurePath) -> Self: ...\n else:\n def rename(self, target: str | PurePath) -> None: ...\n def replace(self, target: str | PurePath) -> None: ...\n\n def resolve(self, strict: bool = False) -> Self: ...\n def rmdir(self) -> None: ...\n def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ...\n if sys.version_info >= (3, 10):\n def hardlink_to(self, target: StrOrBytesPath) -> None: ...\n\n def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ...\n if sys.version_info >= (3, 8):\n def unlink(self, missing_ok: bool = False) -> None: ...\n else:\n def unlink(self) -> None: ...\n\n @classmethod\n def home(cls) -> Self: ...\n def absolute(self) -> Self: ...\n def expanduser(self) -> Self: ...\n def read_bytes(self) -> bytes: ...\n def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ...\n def samefile(self, other_path: StrPath) -> bool: ...\n def write_bytes(self, data: ReadableBuffer) -> int: ...\n if sys.version_info >= (3, 10):\n def write_text(\n self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> int: ...\n else:\n def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ...\n if sys.version_info >= (3, 8) and sys.version_info < (3, 12):\n def link_to(self, target: StrOrBytesPath) -> None: ...\n if sys.version_info >= (3, 12):\n def walk(\n self, top_down: bool = ..., on_error: Callable[[OSError], object] | None = ..., follow_symlinks: bool = ...\n ) -> Iterator[tuple[Self, list[str], list[str]]]: ..."},{"col":0,"comment":"Clear existing data and create new tables.","endLoc":44,"header":"@click.command(\"init-db\")\ndef init_db_command()","id":452,"name":"init_db_command","nodeType":"Function","startLoc":40,"text":"@click.command(\"init-db\")\ndef init_db_command():\n \"\"\"Clear existing data and create new tables.\"\"\"\n init_db()\n click.echo(\"Initialized the database.\")"},{"col":0,"comment":"Register database functions with the Flask app. This is called by\n the application factory.\n ","endLoc":52,"header":"def init_app(app)","id":454,"name":"init_app","nodeType":"Function","startLoc":47,"text":"def init_app(app):\n \"\"\"Register database functions with the Flask app. This is called by\n the application factory.\n \"\"\"\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)"},{"col":0,"comment":"A test client for the app.","endLoc":38,"header":"@pytest.fixture\ndef client(app)","id":456,"name":"client","nodeType":"Function","startLoc":35,"text":"@pytest.fixture\ndef client(app):\n \"\"\"A test client for the app.\"\"\"\n return app.test_client()"},{"fileName":"blueprints.py","filePath":"src/flask","id":457,"nodeType":"File","text":"import os\nimport typing as t\nfrom collections import defaultdict\nfrom functools import update_wrapper\n\nfrom . import typing as ft\nfrom .scaffold import _endpoint_from_view_func\nfrom .scaffold import _sentinel\nfrom .scaffold import Scaffold\nfrom .scaffold import setupmethod\n\nif t.TYPE_CHECKING: # pragma: no cover\n from .app import Flask\n\nDeferredSetupFunction = t.Callable[[\"BlueprintSetupState\"], t.Callable]\nT_after_request = t.TypeVar(\"T_after_request\", bound=ft.AfterRequestCallable)\nT_before_request = t.TypeVar(\"T_before_request\", bound=ft.BeforeRequestCallable)\nT_error_handler = t.TypeVar(\"T_error_handler\", bound=ft.ErrorHandlerCallable)\nT_teardown = t.TypeVar(\"T_teardown\", bound=ft.TeardownCallable)\nT_template_context_processor = t.TypeVar(\n \"T_template_context_processor\", bound=ft.TemplateContextProcessorCallable\n)\nT_template_filter = t.TypeVar(\"T_template_filter\", bound=ft.TemplateFilterCallable)\nT_template_global = t.TypeVar(\"T_template_global\", bound=ft.TemplateGlobalCallable)\nT_template_test = t.TypeVar(\"T_template_test\", bound=ft.TemplateTestCallable)\nT_url_defaults = t.TypeVar(\"T_url_defaults\", bound=ft.URLDefaultCallable)\nT_url_value_preprocessor = t.TypeVar(\n \"T_url_value_preprocessor\", bound=ft.URLValuePreprocessorCallable\n)\n\n\nclass BlueprintSetupState:\n \"\"\"Temporary holder object for registering a blueprint with the\n application. An instance of this class is created by the\n :meth:`~flask.Blueprint.make_setup_state` method and later passed\n to all register callback functions.\n \"\"\"\n\n def __init__(\n self,\n blueprint: \"Blueprint\",\n app: \"Flask\",\n options: t.Any,\n first_registration: bool,\n ) -> None:\n #: a reference to the current application\n self.app = app\n\n #: a reference to the blueprint that created this setup state.\n self.blueprint = blueprint\n\n #: a dictionary with all options that were passed to the\n #: :meth:`~flask.Flask.register_blueprint` method.\n self.options = options\n\n #: as blueprints can be registered multiple times with the\n #: application and not everything wants to be registered\n #: multiple times on it, this attribute can be used to figure\n #: out if the blueprint was registered in the past already.\n self.first_registration = first_registration\n\n subdomain = self.options.get(\"subdomain\")\n if subdomain is None:\n subdomain = self.blueprint.subdomain\n\n #: The subdomain that the blueprint should be active for, ``None``\n #: otherwise.\n self.subdomain = subdomain\n\n url_prefix = self.options.get(\"url_prefix\")\n if url_prefix is None:\n url_prefix = self.blueprint.url_prefix\n #: The prefix that should be used for all URLs defined on the\n #: blueprint.\n self.url_prefix = url_prefix\n\n self.name = self.options.get(\"name\", blueprint.name)\n self.name_prefix = self.options.get(\"name_prefix\", \"\")\n\n #: A dictionary with URL defaults that is added to each and every\n #: URL that was defined with the blueprint.\n self.url_defaults = dict(self.blueprint.url_values_defaults)\n self.url_defaults.update(self.options.get(\"url_defaults\", ()))\n\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[t.Callable] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"A helper method to register a rule (and optionally a view function)\n to the application. The endpoint is automatically prefixed with the\n blueprint's name.\n \"\"\"\n if self.url_prefix is not None:\n if rule:\n rule = \"/\".join((self.url_prefix.rstrip(\"/\"), rule.lstrip(\"/\")))\n else:\n rule = self.url_prefix\n options.setdefault(\"subdomain\", self.subdomain)\n if endpoint is None:\n endpoint = _endpoint_from_view_func(view_func) # type: ignore\n defaults = self.url_defaults\n if \"defaults\" in options:\n defaults = dict(defaults, **options.pop(\"defaults\"))\n\n self.app.add_url_rule(\n rule,\n f\"{self.name_prefix}.{self.name}.{endpoint}\".lstrip(\".\"),\n view_func,\n defaults=defaults,\n **options,\n )\n\n\nclass Blueprint(Scaffold):\n \"\"\"Represents a blueprint, a collection of routes and other\n app-related functions that can be registered on a real application\n later.\n\n A blueprint is an object that allows defining application functions\n without requiring an application object ahead of time. It uses the\n same decorators as :class:`~flask.Flask`, but defers the need for an\n application by recording them for later registration.\n\n Decorating a function with a blueprint creates a deferred function\n that is called with :class:`~flask.blueprints.BlueprintSetupState`\n when the blueprint is registered on an application.\n\n See :doc:`/blueprints` for more information.\n\n :param name: The name of the blueprint. Will be prepended to each\n endpoint name.\n :param import_name: The name of the blueprint package, usually\n ``__name__``. This helps locate the ``root_path`` for the\n blueprint.\n :param static_folder: A folder with static files that should be\n served by the blueprint's static route. The path is relative to\n the blueprint's root path. Blueprint static files are disabled\n by default.\n :param static_url_path: The url to serve static files from.\n Defaults to ``static_folder``. If the blueprint does not have\n a ``url_prefix``, the app's static route will take precedence,\n and the blueprint's static files won't be accessible.\n :param template_folder: A folder with templates that should be added\n to the app's template search path. The path is relative to the\n blueprint's root path. Blueprint templates are disabled by\n default. Blueprint templates have a lower precedence than those\n in the app's templates folder.\n :param url_prefix: A path to prepend to all of the blueprint's URLs,\n to make them distinct from the rest of the app's routes.\n :param subdomain: A subdomain that blueprint routes will match on by\n default.\n :param url_defaults: A dict of default values that blueprint routes\n will receive by default.\n :param root_path: By default, the blueprint will automatically set\n this based on ``import_name``. In certain situations this\n automatic detection can fail, so the path can be specified\n manually instead.\n\n .. versionchanged:: 1.1.0\n Blueprints have a ``cli`` group to register nested CLI commands.\n The ``cli_group`` parameter controls the name of the group under\n the ``flask`` command.\n\n .. versionadded:: 0.7\n \"\"\"\n\n _got_registered_once = False\n\n def __init__(\n self,\n name: str,\n import_name: str,\n static_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n static_url_path: t.Optional[str] = None,\n template_folder: t.Optional[t.Union[str, os.PathLike]] = None,\n url_prefix: t.Optional[str] = None,\n subdomain: t.Optional[str] = None,\n url_defaults: t.Optional[dict] = None,\n root_path: t.Optional[str] = None,\n cli_group: t.Optional[str] = _sentinel, # type: ignore\n ):\n super().__init__(\n import_name=import_name,\n static_folder=static_folder,\n static_url_path=static_url_path,\n template_folder=template_folder,\n root_path=root_path,\n )\n\n if not name:\n raise ValueError(\"'name' may not be empty.\")\n\n if \".\" in name:\n raise ValueError(\"'name' may not contain a dot '.' character.\")\n\n self.name = name\n self.url_prefix = url_prefix\n self.subdomain = subdomain\n self.deferred_functions: t.List[DeferredSetupFunction] = []\n\n if url_defaults is None:\n url_defaults = {}\n\n self.url_values_defaults = url_defaults\n self.cli_group = cli_group\n self._blueprints: t.List[t.Tuple[\"Blueprint\", dict]] = []\n\n def _check_setup_finished(self, f_name: str) -> None:\n if self._got_registered_once:\n raise AssertionError(\n f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n f\" '{self.name}'. It has already been registered at least once, any\"\n \" changes will not be applied consistently.\\n\"\n \"Make sure all imports, decorators, functions, etc. needed to set up\"\n \" the blueprint are done before registering it.\"\n )\n\n @setupmethod\n def record(self, func: t.Callable) -> None:\n \"\"\"Registers a function that is called when the blueprint is\n registered on the application. This function is called with the\n state as argument as returned by the :meth:`make_setup_state`\n method.\n \"\"\"\n self.deferred_functions.append(func)\n\n @setupmethod\n def record_once(self, func: t.Callable) -> None:\n \"\"\"Works like :meth:`record` but wraps the function in another\n function that will ensure the function is only called once. If the\n blueprint is registered a second time on the application, the\n function passed is not called.\n \"\"\"\n\n def wrapper(state: BlueprintSetupState) -> None:\n if state.first_registration:\n func(state)\n\n self.record(update_wrapper(wrapper, func))\n\n def make_setup_state(\n self, app: \"Flask\", options: dict, first_registration: bool = False\n ) -> BlueprintSetupState:\n \"\"\"Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`\n object that is later passed to the register callback functions.\n Subclasses can override this to return a subclass of the setup state.\n \"\"\"\n return BlueprintSetupState(self, app, options, first_registration)\n\n @setupmethod\n def register_blueprint(self, blueprint: \"Blueprint\", **options: t.Any) -> None:\n \"\"\"Register a :class:`~flask.Blueprint` on this blueprint. Keyword\n arguments passed to this method will override the defaults set\n on the blueprint.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with unique names\n for ``url_for``.\n\n .. versionadded:: 2.0\n \"\"\"\n if blueprint is self:\n raise ValueError(\"Cannot register a blueprint on itself\")\n self._blueprints.append((blueprint, options))\n\n def register(self, app: \"Flask\", options: dict) -> None:\n \"\"\"Called by :meth:`Flask.register_blueprint` to register all\n views and callbacks registered on the blueprint with the\n application. Creates a :class:`.BlueprintSetupState` and calls\n each :meth:`record` callback with it.\n\n :param app: The application this blueprint is being registered\n with.\n :param options: Keyword arguments forwarded from\n :meth:`~Flask.register_blueprint`.\n\n .. versionchanged:: 2.3\n Nested blueprints now correctly apply subdomains.\n\n .. versionchanged:: 2.1\n Registering the same blueprint with the same name multiple\n times is an error.\n\n .. versionchanged:: 2.0.1\n Nested blueprints are registered with their dotted name.\n This allows different blueprints with the same name to be\n nested at different locations.\n\n .. versionchanged:: 2.0.1\n The ``name`` option can be used to change the (pre-dotted)\n name the blueprint is registered with. This allows the same\n blueprint to be registered multiple times with unique names\n for ``url_for``.\n \"\"\"\n name_prefix = options.get(\"name_prefix\", \"\")\n self_name = options.get(\"name\", self.name)\n name = f\"{name_prefix}.{self_name}\".lstrip(\".\")\n\n if name in app.blueprints:\n bp_desc = \"this\" if app.blueprints[name] is self else \"a different\"\n existing_at = f\" '{name}'\" if self_name != name else \"\"\n\n raise ValueError(\n f\"The name '{self_name}' is already registered for\"\n f\" {bp_desc} blueprint{existing_at}. Use 'name=' to\"\n f\" provide a unique name.\"\n )\n\n first_bp_registration = not any(bp is self for bp in app.blueprints.values())\n first_name_registration = name not in app.blueprints\n\n app.blueprints[name] = self\n self._got_registered_once = True\n state = self.make_setup_state(app, options, first_bp_registration)\n\n if self.has_static_folder:\n state.add_url_rule(\n f\"{self.static_url_path}/\",\n view_func=self.send_static_file,\n endpoint=\"static\",\n )\n\n # Merge blueprint data into parent.\n if first_bp_registration or first_name_registration:\n\n def extend(bp_dict, parent_dict):\n for key, values in bp_dict.items():\n key = name if key is None else f\"{name}.{key}\"\n parent_dict[key].extend(values)\n\n for key, value in self.error_handler_spec.items():\n key = name if key is None else f\"{name}.{key}\"\n value = defaultdict(\n dict,\n {\n code: {\n exc_class: func for exc_class, func in code_values.items()\n }\n for code, code_values in value.items()\n },\n )\n app.error_handler_spec[key] = value\n\n for endpoint, func in self.view_functions.items():\n app.view_functions[endpoint] = func\n\n extend(self.before_request_funcs, app.before_request_funcs)\n extend(self.after_request_funcs, app.after_request_funcs)\n extend(\n self.teardown_request_funcs,\n app.teardown_request_funcs,\n )\n extend(self.url_default_functions, app.url_default_functions)\n extend(self.url_value_preprocessors, app.url_value_preprocessors)\n extend(self.template_context_processors, app.template_context_processors)\n\n for deferred in self.deferred_functions:\n deferred(state)\n\n cli_resolved_group = options.get(\"cli_group\", self.cli_group)\n\n if self.cli.commands:\n if cli_resolved_group is None:\n app.cli.commands.update(self.cli.commands)\n elif cli_resolved_group is _sentinel:\n self.cli.name = name\n app.cli.add_command(self.cli)\n else:\n self.cli.name = cli_resolved_group\n app.cli.add_command(self.cli)\n\n for blueprint, bp_options in self._blueprints:\n bp_options = bp_options.copy()\n bp_url_prefix = bp_options.get(\"url_prefix\")\n bp_subdomain = bp_options.get(\"subdomain\")\n\n if bp_subdomain is None:\n bp_subdomain = blueprint.subdomain\n\n if state.subdomain is not None and bp_subdomain is not None:\n bp_options[\"subdomain\"] = bp_subdomain + \".\" + state.subdomain\n elif bp_subdomain is not None:\n bp_options[\"subdomain\"] = bp_subdomain\n elif state.subdomain is not None:\n bp_options[\"subdomain\"] = state.subdomain\n\n if bp_url_prefix is None:\n bp_url_prefix = blueprint.url_prefix\n\n if state.url_prefix is not None and bp_url_prefix is not None:\n bp_options[\"url_prefix\"] = (\n state.url_prefix.rstrip(\"/\") + \"/\" + bp_url_prefix.lstrip(\"/\")\n )\n elif bp_url_prefix is not None:\n bp_options[\"url_prefix\"] = bp_url_prefix\n elif state.url_prefix is not None:\n bp_options[\"url_prefix\"] = state.url_prefix\n\n bp_options[\"name_prefix\"] = name\n blueprint.register(app, bp_options)\n\n @setupmethod\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[ft.RouteCallable] = None,\n provide_automatic_options: t.Optional[bool] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for\n full documentation.\n\n The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,\n used with :func:`url_for`, is prefixed with the blueprint's name.\n \"\"\"\n if endpoint and \".\" in endpoint:\n raise ValueError(\"'endpoint' may not contain a dot '.' character.\")\n\n if view_func and hasattr(view_func, \"__name__\") and \".\" in view_func.__name__:\n raise ValueError(\"'view_func' name may not contain a dot '.' character.\")\n\n self.record(\n lambda s: s.add_url_rule(\n rule,\n endpoint,\n view_func,\n provide_automatic_options=provide_automatic_options,\n **options,\n )\n )\n\n @setupmethod\n def app_template_filter(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_filter], T_template_filter]:\n \"\"\"Register a template filter, available in any template rendered by the\n application. Equivalent to :meth:`.Flask.template_filter`.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_filter) -> T_template_filter:\n self.add_app_template_filter(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_app_template_filter(\n self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a template filter, available in any template rendered by the\n application. Works like the :meth:`app_template_filter` decorator. Equivalent to\n :meth:`.Flask.add_template_filter`.\n\n :param name: the optional name of the filter, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.filters[name or f.__name__] = f\n\n self.record_once(register_template)\n\n @setupmethod\n def app_template_test(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_test], T_template_test]:\n \"\"\"Register a template test, available in any template rendered by the\n application. Equivalent to :meth:`.Flask.template_test`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_test) -> T_template_test:\n self.add_app_template_test(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_app_template_test(\n self, f: ft.TemplateTestCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a template test, available in any template rendered by the\n application. Works like the :meth:`app_template_test` decorator. Equivalent to\n :meth:`.Flask.add_template_test`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the test, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.tests[name or f.__name__] = f\n\n self.record_once(register_template)\n\n @setupmethod\n def app_template_global(\n self, name: t.Optional[str] = None\n ) -> t.Callable[[T_template_global], T_template_global]:\n \"\"\"Register a template global, available in any template rendered by the\n application. Equivalent to :meth:`.Flask.template_global`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def decorator(f: T_template_global) -> T_template_global:\n self.add_app_template_global(f, name=name)\n return f\n\n return decorator\n\n @setupmethod\n def add_app_template_global(\n self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None\n ) -> None:\n \"\"\"Register a template global, available in any template rendered by the\n application. Works like the :meth:`app_template_global` decorator. Equivalent to\n :meth:`.Flask.add_template_global`.\n\n .. versionadded:: 0.10\n\n :param name: the optional name of the global, otherwise the\n function name will be used.\n \"\"\"\n\n def register_template(state: BlueprintSetupState) -> None:\n state.app.jinja_env.globals[name or f.__name__] = f\n\n self.record_once(register_template)\n\n @setupmethod\n def before_app_request(self, f: T_before_request) -> T_before_request:\n \"\"\"Like :meth:`before_request`, but before every request, not only those handled\n by the blueprint. Equivalent to :meth:`.Flask.before_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def after_app_request(self, f: T_after_request) -> T_after_request:\n \"\"\"Like :meth:`after_request`, but after every request, not only those handled\n by the blueprint. Equivalent to :meth:`.Flask.after_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def teardown_app_request(self, f: T_teardown) -> T_teardown:\n \"\"\"Like :meth:`teardown_request`, but after every request, not only those\n handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.\n \"\"\"\n self.record_once(\n lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def app_context_processor(\n self, f: T_template_context_processor\n ) -> T_template_context_processor:\n \"\"\"Like :meth:`context_processor`, but for templates rendered by every view, not\n only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.\n \"\"\"\n self.record_once(\n lambda s: s.app.template_context_processors.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def app_errorhandler(\n self, code: t.Union[t.Type[Exception], int]\n ) -> t.Callable[[T_error_handler], T_error_handler]:\n \"\"\"Like :meth:`errorhandler`, but for every request, not only those handled by\n the blueprint. Equivalent to :meth:`.Flask.errorhandler`.\n \"\"\"\n\n def decorator(f: T_error_handler) -> T_error_handler:\n self.record_once(lambda s: s.app.errorhandler(code)(f))\n return f\n\n return decorator\n\n @setupmethod\n def app_url_value_preprocessor(\n self, f: T_url_value_preprocessor\n ) -> T_url_value_preprocessor:\n \"\"\"Like :meth:`url_value_preprocessor`, but for every request, not only those\n handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.\n \"\"\"\n self.record_once(\n lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)\n )\n return f\n\n @setupmethod\n def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:\n \"\"\"Like :meth:`url_defaults`, but for every request, not only those handled by\n the blueprint. Equivalent to :meth:`.Flask.url_defaults`.\n \"\"\"\n self.record_once(\n lambda s: s.app.url_default_functions.setdefault(None, []).append(f)\n )\n return f\n"},{"col":0,"comment":"Internal helper that returns the default endpoint for a given\n function. This always is the function name.\n ","endLoc":778,"header":"def _endpoint_from_view_func(view_func: t.Callable) -> str","id":458,"name":"_endpoint_from_view_func","nodeType":"Function","startLoc":773,"text":"def _endpoint_from_view_func(view_func: t.Callable) -> str:\n \"\"\"Internal helper that returns the default endpoint for a given\n function. This always is the function name.\n \"\"\"\n assert view_func is not None, \"expected view func if endpoint is not provided.\"\n return view_func.__name__"},{"attributeType":"null","col":0,"comment":"null","endLoc":27,"id":459,"name":"_sentinel","nodeType":"Attribute","startLoc":27,"text":"_sentinel"},{"col":0,"comment":"null","endLoc":51,"header":"def setupmethod(f: F) -> F","id":461,"name":"setupmethod","nodeType":"Function","startLoc":44,"text":"def setupmethod(f: F) -> F:\n f_name = f.__name__\n\n def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any:\n self._check_setup_finished(f_name)\n return f(self, *args, **kwargs)\n\n return t.cast(F, update_wrapper(wrapper_func, f))"},{"className":"BaseLoader","col":0,"comment":"Baseclass for all loaders. Subclass this and override `get_source` to\n implement a custom loading mechanism. The environment provides a\n `get_template` method that calls the loader's `load` method to get the\n :class:`Template` object.\n\n A very basic example for a loader that looks up templates on the file\n system could look like this::\n\n from jinja2 import BaseLoader, TemplateNotFound\n from os.path import join, exists, getmtime\n\n class MyLoader(BaseLoader):\n\n def __init__(self, path):\n self.path = path\n\n def get_source(self, environment, template):\n path = join(self.path, template)\n if not exists(path):\n raise TemplateNotFound(template)\n mtime = getmtime(path)\n with file(path) as f:\n source = f.read().decode('utf-8')\n return source, path, lambda: mtime == getmtime(path)\n ","endLoc":138,"id":463,"nodeType":"Class","startLoc":38,"text":"class BaseLoader(object):\n \"\"\"Baseclass for all loaders. Subclass this and override `get_source` to\n implement a custom loading mechanism. The environment provides a\n `get_template` method that calls the loader's `load` method to get the\n :class:`Template` object.\n\n A very basic example for a loader that looks up templates on the file\n system could look like this::\n\n from jinja2 import BaseLoader, TemplateNotFound\n from os.path import join, exists, getmtime\n\n class MyLoader(BaseLoader):\n\n def __init__(self, path):\n self.path = path\n\n def get_source(self, environment, template):\n path = join(self.path, template)\n if not exists(path):\n raise TemplateNotFound(template)\n mtime = getmtime(path)\n with file(path) as f:\n source = f.read().decode('utf-8')\n return source, path, lambda: mtime == getmtime(path)\n \"\"\"\n\n #: if set to `False` it indicates that the loader cannot provide access\n #: to the source of templates.\n #:\n #: .. versionadded:: 2.4\n has_source_access = True\n\n def get_source(self, environment, template):\n \"\"\"Get the template source, filename and reload helper for a template.\n It's passed the environment and template name and has to return a\n tuple in the form ``(source, filename, uptodate)`` or raise a\n `TemplateNotFound` error if it can't locate the template.\n\n The source part of the returned tuple must be the source of the\n template as unicode string or a ASCII bytestring. The filename should\n be the name of the file on the filesystem if it was loaded from there,\n otherwise `None`. The filename is used by python for the tracebacks\n if no loader extension is used.\n\n The last item in the tuple is the `uptodate` function. If auto\n reloading is enabled it's always called to check if the template\n changed. No arguments are passed so the function must store the\n old state somewhere (for example in a closure). If it returns `False`\n the template will be reloaded.\n \"\"\"\n if not self.has_source_access:\n raise RuntimeError(\n \"%s cannot provide access to the source\" % self.__class__.__name__\n )\n raise TemplateNotFound(template)\n\n def list_templates(self):\n \"\"\"Iterates over all templates. If the loader does not support that\n it should raise a :exc:`TypeError` which is the default behavior.\n \"\"\"\n raise TypeError(\"this loader cannot iterate over all templates\")\n\n @internalcode\n def load(self, environment, name, globals=None):\n \"\"\"Loads a template. This method looks up the template in the cache\n or loads one by calling :meth:`get_source`. Subclasses should not\n override this method as loaders working on collections of other\n loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)\n will not call this method but `get_source` directly.\n \"\"\"\n code = None\n if globals is None:\n globals = {}\n\n # first we try to get the source for this template together\n # with the filename and the uptodate function.\n source, filename, uptodate = self.get_source(environment, name)\n\n # try to load the code from the bytecode cache if there is a\n # bytecode cache configured.\n bcc = environment.bytecode_cache\n if bcc is not None:\n bucket = bcc.get_bucket(environment, name, filename, source)\n code = bucket.code\n\n # if we don't have code so far (not cached, no longer up to\n # date) etc. we compile the template\n if code is None:\n code = environment.compile(source, name, filename)\n\n # if the bytecode cache is available and the bucket doesn't\n # have a code so far, we give the bucket the new code and put\n # it back to the bytecode cache.\n if bcc is not None and bucket.code is None:\n bucket.code = code\n bcc.set_bucket(bucket)\n\n return environment.template_class.from_code(\n environment, code, globals, uptodate\n )"},{"col":0,"comment":"A test runner for the app's Click commands.","endLoc":44,"header":"@pytest.fixture\ndef runner(app)","id":464,"name":"runner","nodeType":"Function","startLoc":41,"text":"@pytest.fixture\ndef runner(app):\n \"\"\"A test runner for the app's Click commands.\"\"\"\n return app.test_cli_runner()"},{"className":"object","col":0,"comment":"null","endLoc":127,"id":465,"nodeType":"Class","startLoc":90,"text":"class object:\n __doc__: str | None\n __dict__: dict[str, Any]\n __module__: str\n __annotations__: dict[str, Any]\n @property\n def __class__(self) -> type[Self]: ...\n # Ignore errors about type mismatch between property getter and setter\n @__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811\n def __init__(self) -> None: ...\n def __new__(cls) -> Self: ...\n # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.\n # Overriding them in subclasses has different semantics, even if the override has an identical signature.\n def __setattr__(self, __name: str, __value: Any) -> None: ...\n def __delattr__(self, __name: str) -> None: ...\n def __eq__(self, __value: object) -> bool: ...\n def __ne__(self, __value: object) -> bool: ...\n def __str__(self) -> str: ... # noqa: Y029\n def __repr__(self) -> str: ... # noqa: Y029\n def __hash__(self) -> int: ...\n def __format__(self, __format_spec: str) -> str: ...\n def __getattribute__(self, __name: str) -> Any: ...\n def __sizeof__(self) -> int: ...\n # return type of pickle methods is rather hard to express in the current type system\n # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__\n def __reduce__(self) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 8):\n def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ...\n else:\n def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ...\n if sys.version_info >= (3, 11):\n def __getstate__(self) -> object: ...\n\n def __dir__(self) -> Iterable[str]: ...\n def __init_subclass__(cls) -> None: ...\n @classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"col":0,"comment":"null","endLoc":62,"header":"@pytest.fixture\ndef auth(client)","id":466,"name":"auth","nodeType":"Function","startLoc":60,"text":"@pytest.fixture\ndef auth(client):\n return AuthActions(client)"},{"id":467,"name":"pyproject.toml","nodeType":"TextFile","path":"","text":"[project]\nname = \"Flask\"\ndescription = \"A simple framework for building complex web applications.\"\nreadme = \"README.rst\"\nlicense = {text = \"BSD-3-Clause\"}\nmaintainers = [{name = \"Pallets\", email = \"contact@palletsprojects.com\"}]\nauthors = [{name = \"Armin Ronacher\", email = \"armin.ronacher@active-4.com\"}]\nclassifiers = [\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Web Environment\",\n \"Framework :: Flask\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n \"Topic :: Software Development :: Libraries :: Application Frameworks\",\n]\nrequires-python = \">=3.7\"\ndependencies = [\n \"Werkzeug>=2.2.2\",\n \"Jinja2>=3.0\",\n \"itsdangerous>=2.0\",\n \"click>=8.0\",\n \"blinker>=1.6.2\",\n \"importlib-metadata>=3.6.0; python_version < '3.10'\",\n]\ndynamic = [\"version\"]\n\n[project.urls]\nDonate = \"https://palletsprojects.com/donate\"\nDocumentation = \"https://flask.palletsprojects.com/\"\nChanges = \"https://flask.palletsprojects.com/changes/\"\n\"Source Code\" = \"https://github.com/pallets/flask/\"\n\"Issue Tracker\" = \"https://github.com/pallets/flask/issues/\"\nTwitter = \"https://twitter.com/PalletsTeam\"\nChat = \"https://discord.gg/pallets\"\n\n[project.optional-dependencies]\nasync = [\"asgiref>=3.2\"]\ndotenv = [\"python-dotenv\"]\n\n[project.scripts]\nflask = \"flask.cli:main\"\n\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[tool.setuptools.dynamic]\nversion = {attr = \"flask.__version__\"}\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\nfilterwarnings = [\n \"error\",\n # change in Python 3.12 alpha causes warning from inside pytest\n \"ignore:onerror argument:DeprecationWarning\",\n]\n\n[tool.coverage.run]\nbranch = true\nsource = [\"flask\", \"tests\"]\n\n[tool.coverage.paths]\nsource = [\"src\", \"*/site-packages\"]\n\n[tool.mypy]\npython_version = \"3.7\"\nfiles = [\"src/flask\"]\nshow_error_codes = true\npretty = true\n#strict = true\nallow_redefinition = true\ndisallow_subclassing_any = true\n#disallow_untyped_calls = true\n#disallow_untyped_defs = true\n#disallow_incomplete_defs = true\nno_implicit_optional = true\nlocal_partial_types = true\n#no_implicit_reexport = true\nstrict_equality = true\nwarn_redundant_casts = true\nwarn_unused_configs = true\nwarn_unused_ignores = true\n#warn_return_any = true\n#warn_unreachable = true\n\n[[tool.mypy.overrides]]\nmodule = [\n \"asgiref.*\",\n \"dotenv.*\",\n \"cryptography.*\",\n \"importlib_metadata\",\n]\nignore_missing_imports = true\n"},{"attributeType":"BinaryIO","col":72,"comment":"null","endLoc":11,"id":468,"name":"f","nodeType":"Attribute","startLoc":11,"text":"f"},{"id":469,"name":"LICENSE.rst","nodeType":"TextFile","path":"","text":"Copyright 2010 Pallets\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\nTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"id":470,"name":"tests/test_apps/subdomaintestmodule","nodeType":"Package"},{"fileName":"__init__.py","filePath":"tests/test_apps/subdomaintestmodule","id":471,"nodeType":"File","text":"from flask import Module\n\n\nmod = Module(__name__, \"foo\", subdomain=\"foo\")\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":4,"id":472,"name":"mod","nodeType":"Attribute","startLoc":4,"text":"mod"},{"className":"PurePath","col":0,"comment":"null","endLoc":90,"id":473,"nodeType":"Class","startLoc":25,"text":"class PurePath(PathLike[str]):\n @property\n def parts(self) -> tuple[str, ...]: ...\n @property\n def drive(self) -> str: ...\n @property\n def root(self) -> str: ...\n @property\n def anchor(self) -> str: ...\n @property\n def name(self) -> str: ...\n @property\n def suffix(self) -> str: ...\n @property\n def suffixes(self) -> list[str]: ...\n @property\n def stem(self) -> str: ...\n if sys.version_info >= (3, 12):\n def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...\n def __init__(self, *args: StrPath) -> None: ...\n else:\n def __new__(cls, *args: StrPath) -> Self: ...\n\n def __hash__(self) -> int: ...\n def __fspath__(self) -> str: ...\n def __lt__(self, other: PurePath) -> bool: ...\n def __le__(self, other: PurePath) -> bool: ...\n def __gt__(self, other: PurePath) -> bool: ...\n def __ge__(self, other: PurePath) -> bool: ...\n def __truediv__(self, key: StrPath) -> Self: ...\n def __rtruediv__(self, key: StrPath) -> Self: ...\n def __bytes__(self) -> bytes: ...\n def as_posix(self) -> str: ...\n def as_uri(self) -> str: ...\n def is_absolute(self) -> bool: ...\n def is_reserved(self) -> bool: ...\n if sys.version_info >= (3, 12):\n def is_relative_to(self, __other: StrPath, *_deprecated: StrPath) -> bool: ...\n elif sys.version_info >= (3, 9):\n def is_relative_to(self, *other: StrPath) -> bool: ...\n\n if sys.version_info >= (3, 12):\n def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ...\n else:\n def match(self, path_pattern: str) -> bool: ...\n\n if sys.version_info >= (3, 12):\n def relative_to(self, __other: StrPath, *_deprecated: StrPath, walk_up: bool = False) -> Self: ...\n else:\n def relative_to(self, *other: StrPath) -> Self: ...\n\n def with_name(self, name: str) -> Self: ...\n if sys.version_info >= (3, 9):\n def with_stem(self, stem: str) -> Self: ...\n\n def with_suffix(self, suffix: str) -> Self: ...\n def joinpath(self, *other: StrPath) -> Self: ...\n @property\n def parents(self) -> Sequence[Self]: ...\n @property\n def parent(self) -> Self: ...\n if sys.version_info >= (3, 9) and sys.version_info < (3, 11):\n def __class_getitem__(cls, type: Any) -> GenericAlias: ...\n\n if sys.version_info >= (3, 12):\n def with_segments(self, *args: StrPath) -> Self: ..."},{"className":"BlueprintSetupState","col":0,"comment":"Temporary holder object for registering a blueprint with the\n application. An instance of this class is created by the\n :meth:`~flask.Blueprint.make_setup_state` method and later passed\n to all register callback functions.\n ","endLoc":114,"id":478,"nodeType":"Class","startLoc":32,"text":"class BlueprintSetupState:\n \"\"\"Temporary holder object for registering a blueprint with the\n application. An instance of this class is created by the\n :meth:`~flask.Blueprint.make_setup_state` method and later passed\n to all register callback functions.\n \"\"\"\n\n def __init__(\n self,\n blueprint: \"Blueprint\",\n app: \"Flask\",\n options: t.Any,\n first_registration: bool,\n ) -> None:\n #: a reference to the current application\n self.app = app\n\n #: a reference to the blueprint that created this setup state.\n self.blueprint = blueprint\n\n #: a dictionary with all options that were passed to the\n #: :meth:`~flask.Flask.register_blueprint` method.\n self.options = options\n\n #: as blueprints can be registered multiple times with the\n #: application and not everything wants to be registered\n #: multiple times on it, this attribute can be used to figure\n #: out if the blueprint was registered in the past already.\n self.first_registration = first_registration\n\n subdomain = self.options.get(\"subdomain\")\n if subdomain is None:\n subdomain = self.blueprint.subdomain\n\n #: The subdomain that the blueprint should be active for, ``None``\n #: otherwise.\n self.subdomain = subdomain\n\n url_prefix = self.options.get(\"url_prefix\")\n if url_prefix is None:\n url_prefix = self.blueprint.url_prefix\n #: The prefix that should be used for all URLs defined on the\n #: blueprint.\n self.url_prefix = url_prefix\n\n self.name = self.options.get(\"name\", blueprint.name)\n self.name_prefix = self.options.get(\"name_prefix\", \"\")\n\n #: A dictionary with URL defaults that is added to each and every\n #: URL that was defined with the blueprint.\n self.url_defaults = dict(self.blueprint.url_values_defaults)\n self.url_defaults.update(self.options.get(\"url_defaults\", ()))\n\n def add_url_rule(\n self,\n rule: str,\n endpoint: t.Optional[str] = None,\n view_func: t.Optional[t.Callable] = None,\n **options: t.Any,\n ) -> None:\n \"\"\"A helper method to register a rule (and optionally a view function)\n to the application. The endpoint is automatically prefixed with the\n blueprint's name.\n \"\"\"\n if self.url_prefix is not None:\n if rule:\n rule = \"/\".join((self.url_prefix.rstrip(\"/\"), rule.lstrip(\"/\")))\n else:\n rule = self.url_prefix\n options.setdefault(\"subdomain\", self.subdomain)\n if endpoint is None:\n endpoint = _endpoint_from_view_func(view_func) # type: ignore\n defaults = self.url_defaults\n if \"defaults\" in options:\n defaults = dict(defaults, **options.pop(\"defaults\"))\n\n self.app.add_url_rule(\n rule,\n f\"{self.name_prefix}.{self.name}.{endpoint}\".lstrip(\".\"),\n view_func,\n defaults=defaults,\n **options,\n )"},{"col":4,"comment":"null","endLoc":83,"header":"def __init__(\n self,\n blueprint: \"Blueprint\",\n app: \"Flask\",\n options: t.Any,\n first_registration: bool,\n ) -> None","id":479,"name":"__init__","nodeType":"Function","startLoc":39,"text":"def __init__(\n self,\n blueprint: \"Blueprint\",\n app: \"Flask\",\n options: t.Any,\n first_registration: bool,\n ) -> None:\n #: a reference to the current application\n self.app = app\n\n #: a reference to the blueprint that created this setup state.\n self.blueprint = blueprint\n\n #: a dictionary with all options that were passed to the\n #: :meth:`~flask.Flask.register_blueprint` method.\n self.options = options\n\n #: as blueprints can be registered multiple times with the\n #: application and not everything wants to be registered\n #: multiple times on it, this attribute can be used to figure\n #: out if the blueprint was registered in the past already.\n self.first_registration = first_registration\n\n subdomain = self.options.get(\"subdomain\")\n if subdomain is None:\n subdomain = self.blueprint.subdomain\n\n #: The subdomain that the blueprint should be active for, ``None``\n #: otherwise.\n self.subdomain = subdomain\n\n url_prefix = self.options.get(\"url_prefix\")\n if url_prefix is None:\n url_prefix = self.blueprint.url_prefix\n #: The prefix that should be used for all URLs defined on the\n #: blueprint.\n self.url_prefix = url_prefix\n\n self.name = self.options.get(\"name\", blueprint.name)\n self.name_prefix = self.options.get(\"name_prefix\", \"\")\n\n #: A dictionary with URL defaults that is added to each and every\n #: URL that was defined with the blueprint.\n self.url_defaults = dict(self.blueprint.url_values_defaults)\n self.url_defaults.update(self.options.get(\"url_defaults\", ()))"},{"col":0,"comment":"","endLoc":1,"header":"__init__.py#","id":480,"name":"","nodeType":"Function","startLoc":1,"text":"mod = Module(__name__, \"foo\", subdomain=\"foo\")"},{"id":481,"name":"installation.rst","nodeType":"TextFile","path":"docs","text":"Installation\n============\n\n\nPython Version\n--------------\n\nWe recommend using the latest version of Python. Flask supports Python\n3.7 and newer.\n\n\nDependencies\n------------\n\nThese distributions will be installed automatically when installing Flask.\n\n* `Werkzeug`_ implements WSGI, the standard Python interface between\n applications and servers.\n* `Jinja`_ is a template language that renders the pages your application\n serves.\n* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering\n templates to avoid injection attacks.\n* `ItsDangerous`_ securely signs data to ensure its integrity. This is used\n to protect Flask's session cookie.\n* `Click`_ is a framework for writing command line applications. It provides\n the ``flask`` command and allows adding custom management commands.\n* `Blinker`_ provides support for :doc:`signals`.\n\n.. _Werkzeug: https://palletsprojects.com/p/werkzeug/\n.. _Jinja: https://palletsprojects.com/p/jinja/\n.. _MarkupSafe: https://palletsprojects.com/p/markupsafe/\n.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/\n.. _Click: https://palletsprojects.com/p/click/\n.. _Blinker: https://blinker.readthedocs.io/\n\n\nOptional dependencies\n~~~~~~~~~~~~~~~~~~~~~\n\nThese distributions will not be installed automatically. Flask will detect and\nuse them if you install them.\n\n* `python-dotenv`_ enables support for :ref:`dotenv` when running ``flask``\n commands.\n* `Watchdog`_ provides a faster, more efficient reloader for the development\n server.\n\n.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme\n.. _watchdog: https://pythonhosted.org/watchdog/\n\n\ngreenlet\n~~~~~~~~\n\nYou may choose to use gevent or eventlet with your application. In this\ncase, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is\nrequired.\n\nThese are not minimum supported versions, they only indicate the first\nversions that added necessary features. You should use the latest\nversions of each.\n\n\nVirtual environments\n--------------------\n\nUse a virtual environment to manage the dependencies for your project, both in\ndevelopment and in production.\n\nWhat problem does a virtual environment solve? The more Python projects you\nhave, the more likely it is that you need to work with different versions of\nPython libraries, or even Python itself. Newer versions of libraries for one\nproject can break compatibility in another project.\n\nVirtual environments are independent groups of Python libraries, one for each\nproject. Packages installed for one project will not affect other projects or\nthe operating system's packages.\n\nPython comes bundled with the :mod:`venv` module to create virtual\nenvironments.\n\n\n.. _install-create-env:\n\nCreate an environment\n~~~~~~~~~~~~~~~~~~~~~\n\nCreate a project folder and a :file:`.venv` folder within:\n\n.. tabs::\n\n .. group-tab:: macOS/Linux\n\n .. code-block:: text\n\n $ mkdir myproject\n $ cd myproject\n $ python3 -m venv .venv\n\n .. group-tab:: Windows\n\n .. code-block:: text\n\n > mkdir myproject\n > cd myproject\n > py -3 -m venv .venv\n\n\n.. _install-activate-env:\n\nActivate the environment\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nBefore you work on your project, activate the corresponding environment:\n\n.. tabs::\n\n .. group-tab:: macOS/Linux\n\n .. code-block:: text\n\n $ . .venv/bin/activate\n\n .. group-tab:: Windows\n\n .. code-block:: text\n\n > .venv\\Scripts\\activate\n\nYour shell prompt will change to show the name of the activated\nenvironment.\n\n\nInstall Flask\n-------------\n\nWithin the activated environment, use the following command to install\nFlask:\n\n.. code-block:: sh\n\n $ pip install Flask\n\nFlask is now installed. Check out the :doc:`/quickstart` or go to the\n:doc:`Documentation Overview `.\n"},{"col":4,"comment":"null","endLoc":760,"header":"@property\n def buffer(self) -> BinaryIO","id":482,"name":"buffer","nodeType":"Function","startLoc":759,"text":"@property\n def buffer(self) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":762,"header":"@property\n def encoding(self) -> str","id":483,"name":"encoding","nodeType":"Function","startLoc":761,"text":"@property\n def encoding(self) -> str: ..."},{"col":4,"comment":"null","endLoc":764,"header":"@property\n def errors(self) -> str | None","id":484,"name":"errors","nodeType":"Function","startLoc":763,"text":"@property\n def errors(self) -> str | None: ..."},{"col":4,"comment":"null","endLoc":766,"header":"@property\n def line_buffering(self) -> int","id":485,"name":"line_buffering","nodeType":"Function","startLoc":765,"text":"@property\n def line_buffering(self) -> int: ... # int on PyPy, bool on CPython"},{"col":4,"comment":"null","endLoc":768,"header":"@property\n def newlines(self) -> Any","id":486,"name":"newlines","nodeType":"Function","startLoc":767,"text":"@property\n def newlines(self) -> Any: ... # None, str or tuple"},{"col":4,"comment":"null","endLoc":770,"header":"@abstractmethod\n def __enter__(self) -> TextIO","id":487,"name":"__enter__","nodeType":"Function","startLoc":769,"text":"@abstractmethod\n def __enter__(self) -> TextIO: ..."},{"col":4,"comment":"null","endLoc":645,"header":"@abstractmethod\n def __setitem__(self, __key: _KT, __value: _VT) -> None","id":488,"name":"__setitem__","nodeType":"Function","startLoc":644,"text":"@abstractmethod\n def __setitem__(self, __key: _KT, __value: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":647,"header":"@abstractmethod\n def __delitem__(self, __key: _KT) -> None","id":489,"name":"__delitem__","nodeType":"Function","startLoc":646,"text":"@abstractmethod\n def __delitem__(self, __key: _KT) -> None: ..."},{"col":4,"comment":"null","endLoc":648,"header":"def clear(self) -> None","id":490,"name":"clear","nodeType":"Function","startLoc":648,"text":"def clear(self) -> None: ..."},{"col":4,"comment":"null","endLoc":156,"header":"def __init__(\n self,\n buffer: IO[bytes],\n encoding: str | None = ...,\n errors: str | None = ...,\n newline: str | None = ...,\n line_buffering: bool = ...,\n write_through: bool = ...,\n ) -> None","id":491,"name":"__init__","nodeType":"Function","startLoc":148,"text":"def __init__(\n self,\n buffer: IO[bytes],\n encoding: str | None = ...,\n errors: str | None = ...,\n newline: str | None = ...,\n line_buffering: bool = ...,\n write_through: bool = ...,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":650,"header":"@overload\n def pop(self, __key: _KT) -> _VT","id":492,"name":"pop","nodeType":"Function","startLoc":649,"text":"@overload\n def pop(self, __key: _KT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":652,"header":"@overload\n def pop(self, __key: _KT, default: _VT) -> _VT","id":493,"name":"pop","nodeType":"Function","startLoc":651,"text":"@overload\n def pop(self, __key: _KT, default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":654,"header":"@overload\n def pop(self, __key: _KT, default: _T) -> _VT | _T","id":494,"name":"pop","nodeType":"Function","startLoc":653,"text":"@overload\n def pop(self, __key: _KT, default: _T) -> _VT | _T: ..."},{"col":4,"comment":"null","endLoc":158,"header":"@property\n def buffer(self) -> BinaryIO","id":495,"name":"buffer","nodeType":"Function","startLoc":157,"text":"@property\n def buffer(self) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":160,"header":"@property\n def closed(self) -> bool","id":496,"name":"closed","nodeType":"Function","startLoc":159,"text":"@property\n def closed(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":655,"header":"def popitem(self) -> tuple[_KT, _VT]","id":497,"name":"popitem","nodeType":"Function","startLoc":655,"text":"def popitem(self) -> tuple[_KT, _VT]: ..."},{"col":4,"comment":"null","endLoc":162,"header":"@property\n def line_buffering(self) -> bool","id":498,"name":"line_buffering","nodeType":"Function","startLoc":161,"text":"@property\n def line_buffering(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":663,"header":"@overload\n def setdefault(self: MutableMapping[_KT, _T | None], __key: _KT, __default: None = None) -> _T | None","id":499,"name":"setdefault","nodeType":"Function","startLoc":662,"text":"@overload\n def setdefault(self: MutableMapping[_KT, _T | None], __key: _KT, __default: None = None) -> _T | None: ..."},{"col":4,"comment":"null","endLoc":164,"header":"@property\n def write_through(self) -> bool","id":500,"name":"write_through","nodeType":"Function","startLoc":163,"text":"@property\n def write_through(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":173,"header":"def reconfigure(\n self,\n *,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool | None = None,\n write_through: bool | None = None,\n ) -> None","id":501,"name":"reconfigure","nodeType":"Function","startLoc":165,"text":"def reconfigure(\n self,\n *,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n line_buffering: bool | None = None,\n write_through: bool | None = None,\n ) -> None: ..."},{"col":4,"comment":"null","endLoc":665,"header":"@overload\n def setdefault(self, __key: _KT, __default: _VT) -> _VT","id":502,"name":"setdefault","nodeType":"Function","startLoc":664,"text":"@overload\n def setdefault(self, __key: _KT, __default: _VT) -> _VT: ..."},{"col":4,"comment":"null","endLoc":687,"header":"@overload\n def update(self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None","id":503,"name":"update","nodeType":"Function","startLoc":686,"text":"@overload\n def update(self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":175,"header":"def __enter__(self) -> Self","id":504,"name":"__enter__","nodeType":"Function","startLoc":175,"text":"def __enter__(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":689,"header":"@overload\n def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None","id":505,"name":"update","nodeType":"Function","startLoc":688,"text":"@overload\n def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":176,"header":"def __iter__(self) -> Iterator[str]","id":506,"name":"__iter__","nodeType":"Function","startLoc":176,"text":"def __iter__(self) -> Iterator[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":177,"header":"def __next__(self) -> str","id":507,"name":"__next__","nodeType":"Function","startLoc":177,"text":"def __next__(self) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":691,"header":"@overload\n def update(self, **kwargs: _VT) -> None","id":508,"name":"update","nodeType":"Function","startLoc":690,"text":"@overload\n def update(self, **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":178,"header":"def writelines(self, __lines: Iterable[str]) -> None","id":509,"name":"writelines","nodeType":"Function","startLoc":178,"text":"def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":179,"header":"def readline(self, __size: int = -1) -> str","id":510,"name":"readline","nodeType":"Function","startLoc":179,"text":"def readline(self, __size: int = -1) -> str: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":180,"header":"def readlines(self, __hint: int = -1) -> list[str]","id":511,"name":"readlines","nodeType":"Function","startLoc":180,"text":"def readlines(self, __hint: int = -1) -> list[str]: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":181,"header":"def seek(self, __cookie: int, __whence: int = 0) -> int","id":512,"name":"seek","nodeType":"Function","startLoc":181,"text":"def seek(self, __cookie: int, __whence: int = 0) -> int: ... # stubtest needs this"},{"className":"datetime","col":0,"comment":"null","endLoc":331,"id":513,"nodeType":"Class","startLoc":229,"text":"class datetime(date):\n min: ClassVar[datetime]\n max: ClassVar[datetime]\n def __new__(\n cls,\n year: SupportsIndex,\n month: SupportsIndex,\n day: SupportsIndex,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ...\n @property\n def hour(self) -> int: ...\n @property\n def minute(self) -> int: ...\n @property\n def second(self) -> int: ...\n @property\n def microsecond(self) -> int: ...\n @property\n def tzinfo(self) -> _TzInfo | None: ...\n @property\n def fold(self) -> int: ...\n # On <3.12, the name of the first parameter in the pure-Python implementation\n # didn't match the name in the C implementation,\n # meaning it is only *safe* to pass it as a keyword argument on 3.12+\n if sys.version_info >= (3, 12):\n @classmethod\n def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = ...) -> Self: ...\n else:\n @classmethod\n def fromtimestamp(cls, __timestamp: float, tz: _TzInfo | None = ...) -> Self: ...\n\n @classmethod\n def utcfromtimestamp(cls, __t: float) -> Self: ...\n if sys.version_info >= (3, 8):\n @classmethod\n def now(cls, tz: _TzInfo | None = None) -> Self: ...\n else:\n @overload\n @classmethod\n def now(cls, tz: None = None) -> Self: ...\n @overload\n @classmethod\n def now(cls, tz: _TzInfo) -> datetime: ...\n\n @classmethod\n def utcnow(cls) -> Self: ...\n @classmethod\n def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ...\n def timestamp(self) -> float: ...\n def utctimetuple(self) -> struct_time: ...\n def date(self) -> _Date: ...\n def time(self) -> _Time: ...\n def timetz(self) -> _Time: ...\n def replace(\n self,\n year: SupportsIndex = ...,\n month: SupportsIndex = ...,\n day: SupportsIndex = ...,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ...\n if sys.version_info >= (3, 8):\n def astimezone(self, tz: _TzInfo | None = ...) -> Self: ...\n else:\n def astimezone(self, tz: _TzInfo | None = ...) -> datetime: ...\n\n def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ...\n @classmethod\n def strptime(cls, __date_string: str, __format: str) -> Self: ...\n def utcoffset(self) -> timedelta | None: ...\n def tzname(self) -> str | None: ...\n def dst(self) -> timedelta | None: ...\n def __le__(self, __value: datetime) -> bool: ... # type: ignore[override]\n def __lt__(self, __value: datetime) -> bool: ... # type: ignore[override]\n def __ge__(self, __value: datetime) -> bool: ... # type: ignore[override]\n def __gt__(self, __value: datetime) -> bool: ... # type: ignore[override]\n def __eq__(self, __value: object) -> bool: ...\n def __hash__(self) -> int: ...\n if sys.version_info >= (3, 8):\n @overload # type: ignore[override]\n def __sub__(self, __value: timedelta) -> Self: ...\n @overload\n def __sub__(self: _D, __value: _D) -> timedelta: ...\n else:\n # Prior to Python 3.8, arithmetic operations always returned `datetime`, even in subclasses\n def __add__(self, __value: timedelta) -> datetime: ...\n def __radd__(self, __value: timedelta) -> datetime: ...\n @overload # type: ignore[override]\n def __sub__(self, __value: datetime) -> timedelta: ...\n @overload\n def __sub__(self, __value: timedelta) -> datetime: ..."},{"col":4,"comment":"null","endLoc":184,"header":"def __init__(self, initial_value: str | None = ..., newline: str | None = ...) -> None","id":514,"name":"__init__","nodeType":"Function","startLoc":184,"text":"def __init__(self, initial_value: str | None = ..., newline: str | None = ...) -> None: ..."},{"col":4,"comment":"null","endLoc":189,"header":"def getvalue(self) -> str","id":515,"name":"getvalue","nodeType":"Function","startLoc":189,"text":"def getvalue(self) -> str: ..."},{"attributeType":"null","col":4,"comment":"null","endLoc":188,"id":516,"name":"name","nodeType":"Attribute","startLoc":188,"text":"name"},{"id":517,"name":"design.rst","nodeType":"TextFile","path":"docs","text":"Design Decisions in Flask\n=========================\n\nIf you are curious why Flask does certain things the way it does and not\ndifferently, this section is for you. This should give you an idea about\nsome of the design decisions that may appear arbitrary and surprising at\nfirst, especially in direct comparison with other frameworks.\n\n\nThe Explicit Application Object\n-------------------------------\n\nA Python web application based on WSGI has to have one central callable\nobject that implements the actual application. In Flask this is an\ninstance of the :class:`~flask.Flask` class. Each Flask application has\nto create an instance of this class itself and pass it the name of the\nmodule, but why can't Flask do that itself?\n\nWithout such an explicit application object the following code::\n\n from flask import Flask\n app = Flask(__name__)\n\n @app.route('/')\n def index():\n return 'Hello World!'\n\nWould look like this instead::\n\n from hypothetical_flask import route\n\n @route('/')\n def index():\n return 'Hello World!'\n\nThere are three major reasons for this. The most important one is that\nimplicit application objects require that there may only be one instance at\nthe time. There are ways to fake multiple applications with a single\napplication object, like maintaining a stack of applications, but this\ncauses some problems I won't outline here in detail. Now the question is:\nwhen does a microframework need more than one application at the same\ntime? A good example for this is unit testing. When you want to test\nsomething it can be very helpful to create a minimal application to test\nspecific behavior. When the application object is deleted everything it\nallocated will be freed again.\n\nAnother thing that becomes possible when you have an explicit object lying\naround in your code is that you can subclass the base class\n(:class:`~flask.Flask`) to alter specific behavior. This would not be\npossible without hacks if the object were created ahead of time for you\nbased on a class that is not exposed to you.\n\nBut there is another very important reason why Flask depends on an\nexplicit instantiation of that class: the package name. Whenever you\ncreate a Flask instance you usually pass it `__name__` as package name.\nFlask depends on that information to properly load resources relative\nto your module. With Python's outstanding support for reflection it can\nthen access the package to figure out where the templates and static files\nare stored (see :meth:`~flask.Flask.open_resource`). Now obviously there\nare frameworks around that do not need any configuration and will still be\nable to load templates relative to your application module. But they have\nto use the current working directory for that, which is a very unreliable\nway to determine where the application is. The current working directory\nis process-wide and if you are running multiple applications in one\nprocess (which could happen in a webserver without you knowing) the paths\nwill be off. Worse: many webservers do not set the working directory to\nthe directory of your application but to the document root which does not\nhave to be the same folder.\n\nThe third reason is \"explicit is better than implicit\". That object is\nyour WSGI application, you don't have to remember anything else. If you\nwant to apply a WSGI middleware, just wrap it and you're done (though\nthere are better ways to do that so that you do not lose the reference\nto the application object :meth:`~flask.Flask.wsgi_app`).\n\nFurthermore this design makes it possible to use a factory function to\ncreate the application which is very helpful for unit testing and similar\nthings (:doc:`/patterns/appfactories`).\n\nThe Routing System\n------------------\n\nFlask uses the Werkzeug routing system which was designed to\nautomatically order routes by complexity. This means that you can declare\nroutes in arbitrary order and they will still work as expected. This is a\nrequirement if you want to properly implement decorator based routing\nsince decorators could be fired in undefined order when the application is\nsplit into multiple modules.\n\nAnother design decision with the Werkzeug routing system is that routes\nin Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far\nwith that in that it will automatically redirect to a canonical URL if a route\nis ambiguous.\n\n\nOne Template Engine\n-------------------\n\nFlask decides on one template engine: Jinja2. Why doesn't Flask have a\npluggable template engine interface? You can obviously use a different\ntemplate engine, but Flask will still configure Jinja2 for you. While\nthat limitation that Jinja2 is *always* configured will probably go away,\nthe decision to bundle one template engine and use that will not.\n\nTemplate engines are like programming languages and each of those engines\nhas a certain understanding about how things work. On the surface they\nall work the same: you tell the engine to evaluate a template with a set\nof variables and take the return value as string.\n\nBut that's about where similarities end. Jinja2 for example has an\nextensive filter system, a certain way to do template inheritance,\nsupport for reusable blocks (macros) that can be used from inside\ntemplates and also from Python code, supports iterative template\nrendering, configurable syntax and more. On the other hand an engine\nlike Genshi is based on XML stream evaluation, template inheritance by\ntaking the availability of XPath into account and more. Mako on the\nother hand treats templates similar to Python modules.\n\nWhen it comes to connecting a template engine with an application or\nframework there is more than just rendering templates. For instance,\nFlask uses Jinja2's extensive autoescaping support. Also it provides\nways to access macros from Jinja2 templates.\n\nA template abstraction layer that would not take the unique features of\nthe template engines away is a science on its own and a too large\nundertaking for a microframework like Flask.\n\nFurthermore extensions can then easily depend on one template language\nbeing present. You can easily use your own templating language, but an\nextension could still depend on Jinja itself.\n\n\nWhat does \"micro\" mean?\n-----------------------\n\n“Micro” does not mean that your whole web application has to fit into a single\nPython file (although it certainly can), nor does it mean that Flask is lacking\nin functionality. The \"micro\" in microframework means Flask aims to keep the\ncore simple but extensible. Flask won't make many decisions for you, such as\nwhat database to use. Those decisions that it does make, such as what\ntemplating engine to use, are easy to change. Everything else is up to you, so\nthat Flask can be everything you need and nothing you don't.\n\nBy default, Flask does not include a database abstraction layer, form\nvalidation or anything else where different libraries already exist that can\nhandle that. Instead, Flask supports extensions to add such functionality to\nyour application as if it was implemented in Flask itself. Numerous extensions\nprovide database integration, form validation, upload handling, various open\nauthentication technologies, and more. Flask may be \"micro\", but it's ready for\nproduction use on a variety of needs.\n\nWhy does Flask call itself a microframework and yet it depends on two\nlibraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look\nover to the Ruby side of web development there we have a protocol very\nsimilar to WSGI. Just that it's called Rack there, but besides that it\nlooks very much like a WSGI rendition for Ruby. But nearly all\napplications in Ruby land do not work with Rack directly, but on top of a\nlibrary with the same name. This Rack library has two equivalents in\nPython: WebOb (formerly Paste) and Werkzeug. Paste is still around but\nfrom my understanding it's sort of deprecated in favour of WebOb. The\ndevelopment of WebOb and Werkzeug started side by side with similar ideas\nin mind: be a good implementation of WSGI for other applications to take\nadvantage.\n\nFlask is a framework that takes advantage of the work already done by\nWerkzeug to properly interface WSGI (which can be a complex task at\ntimes). Thanks to recent developments in the Python package\ninfrastructure, packages with dependencies are no longer an issue and\nthere are very few reasons against having libraries that depend on others.\n\n\nThread Locals\n-------------\n\nFlask uses thread local objects (context local objects in fact, they\nsupport greenlet contexts as well) for request, session and an extra\nobject you can put your own things on (:data:`~flask.g`). Why is that and\nisn't that a bad idea?\n\nYes it is usually not such a bright idea to use thread locals. They cause\ntroubles for servers that are not based on the concept of threads and make\nlarge applications harder to maintain. However Flask is just not designed\nfor large applications or asynchronous servers. Flask wants to make it\nquick and easy to write a traditional web application.\n\n\nAsync/await and ASGI support\n----------------------------\n\nFlask supports ``async`` coroutines for view functions by executing the\ncoroutine on a separate thread instead of using an event loop on the\nmain thread as an async-first (ASGI) framework would. This is necessary\nfor Flask to remain backwards compatible with extensions and code built\nbefore ``async`` was introduced into Python. This compromise introduces\na performance cost compared with the ASGI frameworks, due to the\noverhead of the threads.\n\nDue to how tied to WSGI Flask's code is, it's not clear if it's possible\nto make the ``Flask`` class support ASGI and WSGI at the same time. Work\nis currently being done in Werkzeug to work with ASGI, which may\neventually enable support in Flask as well.\n\nSee :doc:`/async-await` for more discussion.\n\n\nWhat Flask is, What Flask is Not\n--------------------------------\n\nFlask will never have a database layer. It will not have a form library\nor anything else in that direction. Flask itself just bridges to Werkzeug\nto implement a proper WSGI application and to Jinja2 to handle templating.\nIt also binds to a few common standard library packages such as logging.\nEverything else is up for extensions.\n\nWhy is this the case? Because people have different preferences and\nrequirements and Flask could not meet those if it would force any of this\ninto the core. The majority of web applications will need a template\nengine in some sort. However not every application needs a SQL database.\n\nAs your codebase grows, you are free to make the design decisions appropriate\nfor your project. Flask will continue to provide a very simple glue layer to\nthe best that Python has to offer. You can implement advanced patterns in\nSQLAlchemy or another database tool, introduce non-relational data persistence\nas appropriate, and take advantage of framework-agnostic tools built for WSGI,\nthe Python web interface.\n\nThe idea of Flask is to build a good foundation for all applications.\nEverything else is up to you or extensions.\n"},{"col":4,"comment":"null","endLoc":27,"header":"@property\n def parts(self) -> tuple[str, ...]","id":518,"name":"parts","nodeType":"Function","startLoc":26,"text":"@property\n def parts(self) -> tuple[str, ...]: ..."},{"col":4,"comment":"null","endLoc":29,"header":"@property\n def drive(self) -> str","id":519,"name":"drive","nodeType":"Function","startLoc":28,"text":"@property\n def drive(self) -> str: ..."},{"col":4,"comment":"null","endLoc":31,"header":"@property\n def root(self) -> str","id":520,"name":"root","nodeType":"Function","startLoc":30,"text":"@property\n def root(self) -> str: ..."},{"col":4,"comment":"null","endLoc":33,"header":"@property\n def anchor(self) -> str","id":521,"name":"anchor","nodeType":"Function","startLoc":32,"text":"@property\n def anchor(self) -> str: ..."},{"col":4,"comment":"null","endLoc":35,"header":"@property\n def name(self) -> str","id":522,"name":"name","nodeType":"Function","startLoc":34,"text":"@property\n def name(self) -> str: ..."},{"col":4,"comment":"null","endLoc":37,"header":"@property\n def suffix(self) -> str","id":523,"name":"suffix","nodeType":"Function","startLoc":36,"text":"@property\n def suffix(self) -> str: ..."},{"col":4,"comment":"null","endLoc":39,"header":"@property\n def suffixes(self) -> list[str]","id":524,"name":"suffixes","nodeType":"Function","startLoc":38,"text":"@property\n def suffixes(self) -> list[str]: ..."},{"col":4,"comment":"null","endLoc":41,"header":"@property\n def stem(self) -> str","id":525,"name":"stem","nodeType":"Function","startLoc":40,"text":"@property\n def stem(self) -> str: ..."},{"col":8,"comment":"null","endLoc":43,"header":"def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self","id":526,"name":"__new__","nodeType":"Function","startLoc":43,"text":"def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ..."},{"col":8,"comment":"null","endLoc":46,"header":"def __new__(cls, *args: StrPath) -> Self","id":527,"name":"__new__","nodeType":"Function","startLoc":46,"text":"def __new__(cls, *args: StrPath) -> Self: ..."},{"col":8,"comment":"null","endLoc":44,"header":"def __init__(self, *args: StrPath) -> None","id":528,"name":"__init__","nodeType":"Function","startLoc":44,"text":"def __init__(self, *args: StrPath) -> None: ..."},{"col":4,"comment":"null","endLoc":48,"header":"def __hash__(self) -> int","id":529,"name":"__hash__","nodeType":"Function","startLoc":48,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":49,"header":"def __fspath__(self) -> str","id":530,"name":"__fspath__","nodeType":"Function","startLoc":49,"text":"def __fspath__(self) -> str: ..."},{"col":4,"comment":"null","endLoc":50,"header":"def __lt__(self, other: PurePath) -> bool","id":531,"name":"__lt__","nodeType":"Function","startLoc":50,"text":"def __lt__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":51,"header":"def __le__(self, other: PurePath) -> bool","id":532,"name":"__le__","nodeType":"Function","startLoc":51,"text":"def __le__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":52,"header":"def __gt__(self, other: PurePath) -> bool","id":533,"name":"__gt__","nodeType":"Function","startLoc":52,"text":"def __gt__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":53,"header":"def __ge__(self, other: PurePath) -> bool","id":534,"name":"__ge__","nodeType":"Function","startLoc":53,"text":"def __ge__(self, other: PurePath) -> bool: ..."},{"col":4,"comment":"null","endLoc":54,"header":"def __truediv__(self, key: StrPath) -> Self","id":535,"name":"__truediv__","nodeType":"Function","startLoc":54,"text":"def __truediv__(self, key: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":55,"header":"def __rtruediv__(self, key: StrPath) -> Self","id":536,"name":"__rtruediv__","nodeType":"Function","startLoc":55,"text":"def __rtruediv__(self, key: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":56,"header":"def __bytes__(self) -> bytes","id":537,"name":"__bytes__","nodeType":"Function","startLoc":56,"text":"def __bytes__(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":57,"header":"def as_posix(self) -> str","id":538,"name":"as_posix","nodeType":"Function","startLoc":57,"text":"def as_posix(self) -> str: ..."},{"col":4,"comment":"null","endLoc":58,"header":"def as_uri(self) -> str","id":539,"name":"as_uri","nodeType":"Function","startLoc":58,"text":"def as_uri(self) -> str: ..."},{"col":4,"comment":"null","endLoc":59,"header":"def is_absolute(self) -> bool","id":540,"name":"is_absolute","nodeType":"Function","startLoc":59,"text":"def is_absolute(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":60,"header":"def is_reserved(self) -> bool","id":541,"name":"is_reserved","nodeType":"Function","startLoc":60,"text":"def is_reserved(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":62,"header":"def is_relative_to(self, __other: StrPath, *_deprecated: StrPath) -> bool","id":542,"name":"is_relative_to","nodeType":"Function","startLoc":62,"text":"def is_relative_to(self, __other: StrPath, *_deprecated: StrPath) -> bool: ..."},{"col":8,"comment":"null","endLoc":64,"header":"def is_relative_to(self, *other: StrPath) -> bool","id":543,"name":"is_relative_to","nodeType":"Function","startLoc":64,"text":"def is_relative_to(self, *other: StrPath) -> bool: ..."},{"col":8,"comment":"null","endLoc":67,"header":"def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool","id":544,"name":"match","nodeType":"Function","startLoc":67,"text":"def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ..."},{"col":8,"comment":"null","endLoc":69,"header":"def match(self, path_pattern: str) -> bool","id":545,"name":"match","nodeType":"Function","startLoc":69,"text":"def match(self, path_pattern: str) -> bool: ..."},{"col":8,"comment":"null","endLoc":72,"header":"def relative_to(self, __other: StrPath, *_deprecated: StrPath, walk_up: bool = False) -> Self","id":546,"name":"relative_to","nodeType":"Function","startLoc":72,"text":"def relative_to(self, __other: StrPath, *_deprecated: StrPath, walk_up: bool = False) -> Self: ..."},{"col":8,"comment":"null","endLoc":74,"header":"def relative_to(self, *other: StrPath) -> Self","id":547,"name":"relative_to","nodeType":"Function","startLoc":74,"text":"def relative_to(self, *other: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":76,"header":"def with_name(self, name: str) -> Self","id":548,"name":"with_name","nodeType":"Function","startLoc":76,"text":"def with_name(self, name: str) -> Self: ..."},{"col":8,"comment":"null","endLoc":78,"header":"def with_stem(self, stem: str) -> Self","id":549,"name":"with_stem","nodeType":"Function","startLoc":78,"text":"def with_stem(self, stem: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":80,"header":"def with_suffix(self, suffix: str) -> Self","id":550,"name":"with_suffix","nodeType":"Function","startLoc":80,"text":"def with_suffix(self, suffix: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":81,"header":"def joinpath(self, *other: StrPath) -> Self","id":551,"name":"joinpath","nodeType":"Function","startLoc":81,"text":"def joinpath(self, *other: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":83,"header":"@property\n def parents(self) -> Sequence[Self]","id":552,"name":"parents","nodeType":"Function","startLoc":82,"text":"@property\n def parents(self) -> Sequence[Self]: ..."},{"col":4,"comment":"null","endLoc":85,"header":"@property\n def parent(self) -> Self","id":553,"name":"parent","nodeType":"Function","startLoc":84,"text":"@property\n def parent(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":87,"header":"def __class_getitem__(cls, type: Any) -> GenericAlias","id":554,"name":"__class_getitem__","nodeType":"Function","startLoc":87,"text":"def __class_getitem__(cls, type: Any) -> GenericAlias: ..."},{"col":8,"comment":"null","endLoc":90,"header":"def with_segments(self, *args: StrPath) -> Self","id":555,"name":"with_segments","nodeType":"Function","startLoc":90,"text":"def with_segments(self, *args: StrPath) -> Self: ..."},{"col":4,"comment":"null","endLoc":244,"header":"def __new__(\n cls,\n year: SupportsIndex,\n month: SupportsIndex,\n day: SupportsIndex,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self","id":556,"name":"__new__","nodeType":"Function","startLoc":232,"text":"def __new__(\n cls,\n year: SupportsIndex,\n month: SupportsIndex,\n day: SupportsIndex,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ..."},{"col":4,"comment":"null","endLoc":246,"header":"@property\n def hour(self) -> int","id":557,"name":"hour","nodeType":"Function","startLoc":245,"text":"@property\n def hour(self) -> int: ..."},{"col":4,"comment":"null","endLoc":248,"header":"@property\n def minute(self) -> int","id":558,"name":"minute","nodeType":"Function","startLoc":247,"text":"@property\n def minute(self) -> int: ..."},{"col":4,"comment":"null","endLoc":250,"header":"@property\n def second(self) -> int","id":559,"name":"second","nodeType":"Function","startLoc":249,"text":"@property\n def second(self) -> int: ..."},{"col":4,"comment":"null","endLoc":252,"header":"@property\n def microsecond(self) -> int","id":560,"name":"microsecond","nodeType":"Function","startLoc":251,"text":"@property\n def microsecond(self) -> int: ..."},{"col":4,"comment":"null","endLoc":254,"header":"@property\n def tzinfo(self) -> _TzInfo | None","id":561,"name":"tzinfo","nodeType":"Function","startLoc":253,"text":"@property\n def tzinfo(self) -> _TzInfo | None: ..."},{"col":4,"comment":"null","endLoc":256,"header":"@property\n def fold(self) -> int","id":562,"name":"fold","nodeType":"Function","startLoc":255,"text":"@property\n def fold(self) -> int: ..."},{"col":4,"comment":"null","endLoc":96,"header":"def __new__(cls, *args: StrPath, **kwargs: Any) -> Self","id":563,"name":"__new__","nodeType":"Function","startLoc":96,"text":"def __new__(cls, *args: StrPath, **kwargs: Any) -> Self: ..."},{"col":8,"comment":"null","endLoc":262,"header":"@classmethod\n def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = ...) -> Self","id":564,"name":"fromtimestamp","nodeType":"Function","startLoc":261,"text":"@classmethod\n def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":97,"header":"def __enter__(self) -> Self","id":565,"name":"__enter__","nodeType":"Function","startLoc":97,"text":"def __enter__(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":265,"header":"@classmethod\n def fromtimestamp(cls, __timestamp: float, tz: _TzInfo | None = ...) -> Self","id":566,"name":"fromtimestamp","nodeType":"Function","startLoc":264,"text":"@classmethod\n def fromtimestamp(cls, __timestamp: float, tz: _TzInfo | None = ...) -> Self: ..."},{"col":4,"comment":"null","endLoc":98,"header":"def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None","id":567,"name":"__exit__","nodeType":"Function","startLoc":98,"text":"def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ..."},{"col":4,"comment":"null","endLoc":268,"header":"@classmethod\n def utcfromtimestamp(cls, __t: float) -> Self","id":568,"name":"utcfromtimestamp","nodeType":"Function","startLoc":267,"text":"@classmethod\n def utcfromtimestamp(cls, __t: float) -> Self: ..."},{"col":4,"comment":"null","endLoc":100,"header":"@classmethod\n def cwd(cls) -> Self","id":569,"name":"cwd","nodeType":"Function","startLoc":99,"text":"@classmethod\n def cwd(cls) -> Self: ..."},{"col":8,"comment":"null","endLoc":271,"header":"@classmethod\n def now(cls, tz: _TzInfo | None = None) -> Self","id":570,"name":"now","nodeType":"Function","startLoc":270,"text":"@classmethod\n def now(cls, tz: _TzInfo | None = None) -> Self: ..."},{"col":8,"comment":"null","endLoc":102,"header":"def stat(self, *, follow_symlinks: bool = True) -> stat_result","id":571,"name":"stat","nodeType":"Function","startLoc":102,"text":"def stat(self, *, follow_symlinks: bool = True) -> stat_result: ..."},{"col":8,"comment":"null","endLoc":275,"header":"@overload\n @classmethod\n def now(cls, tz: None = None) -> Self","id":572,"name":"now","nodeType":"Function","startLoc":273,"text":"@overload\n @classmethod\n def now(cls, tz: None = None) -> Self: ..."},{"col":8,"comment":"null","endLoc":278,"header":"@overload\n @classmethod\n def now(cls, tz: _TzInfo) -> datetime","id":573,"name":"now","nodeType":"Function","startLoc":276,"text":"@overload\n @classmethod\n def now(cls, tz: _TzInfo) -> datetime: ..."},{"col":8,"comment":"null","endLoc":105,"header":"def stat(self) -> stat_result","id":574,"name":"stat","nodeType":"Function","startLoc":105,"text":"def stat(self) -> stat_result: ..."},{"id":575,"name":".editorconfig","nodeType":"TextFile","path":"","text":"root = true\n\n[*]\nindent_style = space\nindent_size = 4\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nend_of_line = lf\ncharset = utf-8\nmax_line_length = 88\n\n[*.{yml,yaml,json,js,css,html}]\nindent_size = 2\n"},{"col":8,"comment":"null","endLoc":103,"header":"def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None","id":576,"name":"chmod","nodeType":"Function","startLoc":103,"text":"def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ..."},{"col":4,"comment":"null","endLoc":281,"header":"@classmethod\n def utcnow(cls) -> Self","id":577,"name":"utcnow","nodeType":"Function","startLoc":280,"text":"@classmethod\n def utcnow(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":283,"header":"@classmethod\n def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self","id":578,"name":"combine","nodeType":"Function","startLoc":282,"text":"@classmethod\n def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ..."},{"col":8,"comment":"null","endLoc":106,"header":"def chmod(self, mode: int) -> None","id":579,"name":"chmod","nodeType":"Function","startLoc":106,"text":"def chmod(self, mode: int) -> None: ..."},{"col":8,"comment":"null","endLoc":109,"header":"def exists(self, *, follow_symlinks: bool = True) -> bool","id":580,"name":"exists","nodeType":"Function","startLoc":109,"text":"def exists(self, *, follow_symlinks: bool = True) -> bool: ..."},{"col":4,"comment":"null","endLoc":284,"header":"def timestamp(self) -> float","id":581,"name":"timestamp","nodeType":"Function","startLoc":284,"text":"def timestamp(self) -> float: ..."},{"col":8,"comment":"null","endLoc":113,"header":"def exists(self) -> bool","id":582,"name":"exists","nodeType":"Function","startLoc":113,"text":"def exists(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":285,"header":"def utctimetuple(self) -> struct_time","id":583,"name":"utctimetuple","nodeType":"Function","startLoc":285,"text":"def utctimetuple(self) -> struct_time: ..."},{"col":8,"comment":"null","endLoc":110,"header":"def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]","id":584,"name":"glob","nodeType":"Function","startLoc":110,"text":"def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ..."},{"col":4,"comment":"null","endLoc":286,"header":"def date(self) -> _Date","id":585,"name":"date","nodeType":"Function","startLoc":286,"text":"def date(self) -> _Date: ..."},{"col":4,"comment":"null","endLoc":287,"header":"def time(self) -> _Time","id":586,"name":"time","nodeType":"Function","startLoc":287,"text":"def time(self) -> _Time: ..."},{"col":4,"comment":"null","endLoc":288,"header":"def timetz(self) -> _Time","id":587,"name":"timetz","nodeType":"Function","startLoc":288,"text":"def timetz(self) -> _Time: ..."},{"col":8,"comment":"null","endLoc":114,"header":"def glob(self, pattern: str) -> Generator[Self, None, None]","id":588,"name":"glob","nodeType":"Function","startLoc":114,"text":"def glob(self, pattern: str) -> Generator[Self, None, None]: ..."},{"col":4,"comment":"null","endLoc":301,"header":"def replace(\n self,\n year: SupportsIndex = ...,\n month: SupportsIndex = ...,\n day: SupportsIndex = ...,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self","id":589,"name":"replace","nodeType":"Function","startLoc":289,"text":"def replace(\n self,\n year: SupportsIndex = ...,\n month: SupportsIndex = ...,\n day: SupportsIndex = ...,\n hour: SupportsIndex = ...,\n minute: SupportsIndex = ...,\n second: SupportsIndex = ...,\n microsecond: SupportsIndex = ...,\n tzinfo: _TzInfo | None = ...,\n *,\n fold: int = ...,\n ) -> Self: ..."},{"col":8,"comment":"null","endLoc":111,"header":"def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]","id":590,"name":"rglob","nodeType":"Function","startLoc":111,"text":"def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ..."},{"col":8,"comment":"null","endLoc":115,"header":"def rglob(self, pattern: str) -> Generator[Self, None, None]","id":591,"name":"rglob","nodeType":"Function","startLoc":115,"text":"def rglob(self, pattern: str) -> Generator[Self, None, None]: ..."},{"col":8,"comment":"null","endLoc":303,"header":"def astimezone(self, tz: _TzInfo | None = ...) -> Self","id":592,"name":"astimezone","nodeType":"Function","startLoc":303,"text":"def astimezone(self, tz: _TzInfo | None = ...) -> Self: ..."},{"col":8,"comment":"null","endLoc":305,"header":"def astimezone(self, tz: _TzInfo | None = ...) -> datetime","id":593,"name":"astimezone","nodeType":"Function","startLoc":305,"text":"def astimezone(self, tz: _TzInfo | None = ...) -> datetime: ..."},{"col":4,"comment":"null","endLoc":117,"header":"def is_dir(self) -> bool","id":594,"name":"is_dir","nodeType":"Function","startLoc":117,"text":"def is_dir(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":118,"header":"def is_file(self) -> bool","id":595,"name":"is_file","nodeType":"Function","startLoc":118,"text":"def is_file(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":307,"header":"def isoformat(self, sep: str = ..., timespec: str = ...) -> str","id":596,"name":"isoformat","nodeType":"Function","startLoc":307,"text":"def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ..."},{"col":4,"comment":"null","endLoc":119,"header":"def is_symlink(self) -> bool","id":597,"name":"is_symlink","nodeType":"Function","startLoc":119,"text":"def is_symlink(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":309,"header":"@classmethod\n def strptime(cls, __date_string: str, __format: str) -> Self","id":598,"name":"strptime","nodeType":"Function","startLoc":308,"text":"@classmethod\n def strptime(cls, __date_string: str, __format: str) -> Self: ..."},{"col":4,"comment":"null","endLoc":120,"header":"def is_socket(self) -> bool","id":599,"name":"is_socket","nodeType":"Function","startLoc":120,"text":"def is_socket(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":121,"header":"def is_fifo(self) -> bool","id":600,"name":"is_fifo","nodeType":"Function","startLoc":121,"text":"def is_fifo(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":310,"header":"def utcoffset(self) -> timedelta | None","id":601,"name":"utcoffset","nodeType":"Function","startLoc":310,"text":"def utcoffset(self) -> timedelta | None: ..."},{"col":4,"comment":"null","endLoc":122,"header":"def is_block_device(self) -> bool","id":602,"name":"is_block_device","nodeType":"Function","startLoc":122,"text":"def is_block_device(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":311,"header":"def tzname(self) -> str | None","id":603,"name":"tzname","nodeType":"Function","startLoc":311,"text":"def tzname(self) -> str | None: ..."},{"col":4,"comment":"null","endLoc":123,"header":"def is_char_device(self) -> bool","id":604,"name":"is_char_device","nodeType":"Function","startLoc":123,"text":"def is_char_device(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":312,"header":"def dst(self) -> timedelta | None","id":605,"name":"dst","nodeType":"Function","startLoc":312,"text":"def dst(self) -> timedelta | None: ..."},{"col":8,"comment":"null","endLoc":125,"header":"def is_junction(self) -> bool","id":606,"name":"is_junction","nodeType":"Function","startLoc":125,"text":"def is_junction(self) -> bool: ..."},{"id":607,"name":"tests/test_apps","nodeType":"Package"},{"col":4,"comment":"null","endLoc":313,"header":"def __le__(self, __value: datetime) -> bool","id":608,"name":"__le__","nodeType":"Function","startLoc":313,"text":"def __le__(self, __value: datetime) -> bool: ... # type: ignore[override]"},{"id":609,"name":".env","nodeType":"TextFile","path":"tests/test_apps","text":"FOO=env\nSPAM=1\nEGGS=2\nHAM=火腿\n"},{"col":4,"comment":"null","endLoc":127,"header":"def iterdir(self) -> Generator[Self, None, None]","id":610,"name":"iterdir","nodeType":"Function","startLoc":127,"text":"def iterdir(self) -> Generator[Self, None, None]: ..."},{"col":4,"comment":"null","endLoc":314,"header":"def __lt__(self, __value: datetime) -> bool","id":611,"name":"__lt__","nodeType":"Function","startLoc":314,"text":"def __lt__(self, __value: datetime) -> bool: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":128,"header":"def lchmod(self, mode: int) -> None","id":612,"name":"lchmod","nodeType":"Function","startLoc":128,"text":"def lchmod(self, mode: int) -> None: ..."},{"col":4,"comment":"null","endLoc":315,"header":"def __ge__(self, __value: datetime) -> bool","id":613,"name":"__ge__","nodeType":"Function","startLoc":315,"text":"def __ge__(self, __value: datetime) -> bool: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":129,"header":"def lstat(self) -> stat_result","id":614,"name":"lstat","nodeType":"Function","startLoc":129,"text":"def lstat(self) -> stat_result: ..."},{"col":4,"comment":"null","endLoc":316,"header":"def __gt__(self, __value: datetime) -> bool","id":615,"name":"__gt__","nodeType":"Function","startLoc":316,"text":"def __gt__(self, __value: datetime) -> bool: ... # type: ignore[override]"},{"col":4,"comment":"null","endLoc":130,"header":"def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None","id":616,"name":"mkdir","nodeType":"Function","startLoc":130,"text":"def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ..."},{"col":4,"comment":"null","endLoc":317,"header":"def __eq__(self, __value: object) -> bool","id":617,"name":"__eq__","nodeType":"Function","startLoc":317,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":318,"header":"def __hash__(self) -> int","id":618,"name":"__hash__","nodeType":"Function","startLoc":318,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":142,"header":"@overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper","id":619,"name":"open","nodeType":"Function","startLoc":134,"text":"@overload\n def open(\n self,\n mode: OpenTextMode = \"r\",\n buffering: int = -1,\n encoding: str | None = None,\n errors: str | None = None,\n newline: str | None = None,\n ) -> TextIOWrapper: ..."},{"col":8,"comment":"null","endLoc":321,"header":"@overload # type: ignore[override]\n def __sub__(self, __value: timedelta) -> Self","id":620,"name":"__sub__","nodeType":"Function","startLoc":320,"text":"@overload # type: ignore[override]\n def __sub__(self, __value: timedelta) -> Self: ..."},{"col":8,"comment":"null","endLoc":323,"header":"@overload\n def __sub__(self: _D, __value: _D) -> timedelta","id":621,"name":"__sub__","nodeType":"Function","startLoc":322,"text":"@overload\n def __sub__(self: _D, __value: _D) -> timedelta: ..."},{"col":8,"comment":"null","endLoc":329,"header":"@overload # type: ignore[override]\n def __sub__(self, __value: datetime) -> timedelta","id":622,"name":"__sub__","nodeType":"Function","startLoc":328,"text":"@overload # type: ignore[override]\n def __sub__(self, __value: datetime) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":147,"header":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO","id":623,"name":"open","nodeType":"Function","startLoc":144,"text":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n ) -> FileIO: ..."},{"col":8,"comment":"null","endLoc":331,"header":"@overload\n def __sub__(self, __value: timedelta) -> datetime","id":624,"name":"__sub__","nodeType":"Function","startLoc":330,"text":"@overload\n def __sub__(self, __value: timedelta) -> datetime: ..."},{"col":8,"comment":"null","endLoc":326,"header":"def __add__(self, __value: timedelta) -> datetime","id":625,"name":"__add__","nodeType":"Function","startLoc":326,"text":"def __add__(self, __value: timedelta) -> datetime: ..."},{"col":4,"comment":"null","endLoc":157,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom","id":626,"name":"open","nodeType":"Function","startLoc":149,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeUpdating,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedRandom: ..."},{"col":8,"comment":"null","endLoc":327,"header":"def __radd__(self, __value: timedelta) -> datetime","id":627,"name":"__radd__","nodeType":"Function","startLoc":327,"text":"def __radd__(self, __value: timedelta) -> datetime: ..."},{"col":4,"comment":"null","endLoc":166,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter","id":628,"name":"open","nodeType":"Function","startLoc":158,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeWriting,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedWriter: ..."},{"attributeType":"datetime","col":4,"comment":"null","endLoc":230,"id":629,"name":"min","nodeType":"Attribute","startLoc":230,"text":"min"},{"col":4,"comment":"null","endLoc":175,"header":"@overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader","id":630,"name":"open","nodeType":"Function","startLoc":167,"text":"@overload\n def open(\n self,\n mode: OpenBinaryModeReading,\n buffering: Literal[-1, 1] = -1,\n encoding: None = None,\n errors: None = None,\n newline: None = None,\n ) -> BufferedReader: ..."},{"id":631,"name":".flaskenv","nodeType":"TextFile","path":"tests/test_apps","text":"FOO=flaskenv\nBAR=bar\nEGGS=0\n"},{"col":4,"comment":"null","endLoc":180,"header":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO","id":632,"name":"open","nodeType":"Function","startLoc":177,"text":"@overload\n def open(\n self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n ) -> BinaryIO: ..."},{"col":4,"comment":"null","endLoc":185,"header":"@overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]","id":633,"name":"open","nodeType":"Function","startLoc":182,"text":"@overload\n def open(\n self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> IO[Any]: ..."},{"col":8,"comment":"null","endLoc":189,"header":"def owner(self) -> str","id":634,"name":"owner","nodeType":"Function","startLoc":189,"text":"def owner(self) -> str: ..."},{"col":8,"comment":"null","endLoc":190,"header":"def group(self) -> str","id":635,"name":"group","nodeType":"Function","startLoc":190,"text":"def group(self) -> str: ..."},{"col":8,"comment":"null","endLoc":195,"header":"def is_mount(self) -> bool","id":636,"name":"is_mount","nodeType":"Function","startLoc":195,"text":"def is_mount(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":198,"header":"def readlink(self) -> Self","id":637,"name":"readlink","nodeType":"Function","startLoc":198,"text":"def readlink(self) -> Self: ..."},{"col":8,"comment":"null","endLoc":200,"header":"def rename(self, target: str | PurePath) -> Self","id":638,"name":"rename","nodeType":"Function","startLoc":200,"text":"def rename(self, target: str | PurePath) -> Self: ..."},{"col":8,"comment":"null","endLoc":203,"header":"def rename(self, target: str | PurePath) -> None","id":639,"name":"rename","nodeType":"Function","startLoc":203,"text":"def rename(self, target: str | PurePath) -> None: ..."},{"col":8,"comment":"null","endLoc":201,"header":"def replace(self, target: str | PurePath) -> Self","id":640,"name":"replace","nodeType":"Function","startLoc":201,"text":"def replace(self, target: str | PurePath) -> Self: ..."},{"col":8,"comment":"null","endLoc":204,"header":"def replace(self, target: str | PurePath) -> None","id":641,"name":"replace","nodeType":"Function","startLoc":204,"text":"def replace(self, target: str | PurePath) -> None: ..."},{"col":4,"comment":"null","endLoc":206,"header":"def resolve(self, strict: bool = False) -> Self","id":642,"name":"resolve","nodeType":"Function","startLoc":206,"text":"def resolve(self, strict: bool = False) -> Self: ..."},{"col":4,"comment":"null","endLoc":207,"header":"def rmdir(self) -> None","id":643,"name":"rmdir","nodeType":"Function","startLoc":207,"text":"def rmdir(self) -> None: ..."},{"col":4,"comment":"null","endLoc":208,"header":"def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None","id":644,"name":"symlink_to","nodeType":"Function","startLoc":208,"text":"def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ..."},{"col":8,"comment":"null","endLoc":210,"header":"def hardlink_to(self, target: StrOrBytesPath) -> None","id":645,"name":"hardlink_to","nodeType":"Function","startLoc":210,"text":"def hardlink_to(self, target: StrOrBytesPath) -> None: ..."},{"col":4,"comment":"null","endLoc":212,"header":"def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None","id":646,"name":"touch","nodeType":"Function","startLoc":212,"text":"def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ..."},{"col":8,"comment":"null","endLoc":214,"header":"def unlink(self, missing_ok: bool = False) -> None","id":647,"name":"unlink","nodeType":"Function","startLoc":214,"text":"def unlink(self, missing_ok: bool = False) -> None: ..."},{"col":8,"comment":"null","endLoc":216,"header":"def unlink(self) -> None","id":648,"name":"unlink","nodeType":"Function","startLoc":216,"text":"def unlink(self) -> None: ..."},{"col":4,"comment":"null","endLoc":219,"header":"@classmethod\n def home(cls) -> Self","id":649,"name":"home","nodeType":"Function","startLoc":218,"text":"@classmethod\n def home(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":220,"header":"def absolute(self) -> Self","id":650,"name":"absolute","nodeType":"Function","startLoc":220,"text":"def absolute(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":221,"header":"def expanduser(self) -> Self","id":651,"name":"expanduser","nodeType":"Function","startLoc":221,"text":"def expanduser(self) -> Self: ..."},{"col":4,"comment":"null","endLoc":222,"header":"def read_bytes(self) -> bytes","id":652,"name":"read_bytes","nodeType":"Function","startLoc":222,"text":"def read_bytes(self) -> bytes: ..."},{"col":4,"comment":"null","endLoc":223,"header":"def read_text(self, encoding: str | None = None, errors: str | None = None) -> str","id":653,"name":"read_text","nodeType":"Function","startLoc":223,"text":"def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ..."},{"col":4,"comment":"null","endLoc":224,"header":"def samefile(self, other_path: StrPath) -> bool","id":654,"name":"samefile","nodeType":"Function","startLoc":224,"text":"def samefile(self, other_path: StrPath) -> bool: ..."},{"col":4,"comment":"null","endLoc":225,"header":"def write_bytes(self, data: ReadableBuffer) -> int","id":655,"name":"write_bytes","nodeType":"Function","startLoc":225,"text":"def write_bytes(self, data: ReadableBuffer) -> int: ..."},{"col":8,"comment":"null","endLoc":229,"header":"def write_text(\n self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> int","id":656,"name":"write_text","nodeType":"Function","startLoc":227,"text":"def write_text(\n self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n ) -> int: ..."},{"col":8,"comment":"null","endLoc":231,"header":"def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int","id":657,"name":"write_text","nodeType":"Function","startLoc":231,"text":"def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ..."},{"col":8,"comment":"null","endLoc":233,"header":"def link_to(self, target: StrOrBytesPath) -> None","id":658,"name":"link_to","nodeType":"Function","startLoc":233,"text":"def link_to(self, target: StrOrBytesPath) -> None: ..."},{"col":8,"comment":"null","endLoc":237,"header":"def walk(\n self, top_down: bool = ..., on_error: Callable[[OSError], object] | None = ..., follow_symlinks: bool = ...\n ) -> Iterator[tuple[Self, list[str], list[str]]]","id":659,"name":"walk","nodeType":"Function","startLoc":235,"text":"def walk(\n self, top_down: bool = ..., on_error: Callable[[OSError], object] | None = ..., follow_symlinks: bool = ...\n ) -> Iterator[tuple[Self, list[str], list[str]]]: ..."},{"col":4,"comment":"Convert the class into a view function that can be registered\n for a route.\n\n By default, the generated view will create a new instance of the\n view class for every request and call its\n :meth:`dispatch_request` method. If the view class sets\n :attr:`init_every_request` to ``False``, the same instance will\n be used for every request.\n\n Except for ``name``, all other arguments passed to this method\n are forwarded to the view class ``__init__`` method.\n\n .. versionchanged:: 2.2\n Added the ``init_every_request`` class attribute.\n ","endLoc":132,"header":"@classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> ft.RouteCallable","id":660,"name":"as_view","nodeType":"Function","startLoc":82,"text":"@classmethod\n def as_view(\n cls, name: str, *class_args: t.Any, **class_kwargs: t.Any\n ) -> ft.RouteCallable:\n \"\"\"Convert the class into a view function that can be registered\n for a route.\n\n By default, the generated view will create a new instance of the\n view class for every request and call its\n :meth:`dispatch_request` method. If the view class sets\n :attr:`init_every_request` to ``False``, the same instance will\n be used for every request.\n\n Except for ``name``, all other arguments passed to this method\n are forwarded to the view class ``__init__`` method.\n\n .. versionchanged:: 2.2\n Added the ``init_every_request`` class attribute.\n \"\"\"\n if cls.init_every_request:\n\n def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n self = view.view_class( # type: ignore[attr-defined]\n *class_args, **class_kwargs\n )\n return current_app.ensure_sync(self.dispatch_request)(**kwargs)\n\n else:\n self = cls(*class_args, **class_kwargs)\n\n def view(**kwargs: t.Any) -> ft.ResponseReturnValue:\n return current_app.ensure_sync(self.dispatch_request)(**kwargs)\n\n if cls.decorators:\n view.__name__ = name\n view.__module__ = cls.__module__\n for decorator in cls.decorators:\n view = decorator(view)\n\n # We attach the view class to the view function for two reasons:\n # first of all it allows us to easily figure out what class-based\n # view this thing came from, secondly it's also used for instantiating\n # the view class so you can actually replace it with something else\n # for testing purposes and debugging.\n view.view_class = cls # type: ignore\n view.__name__ = name\n view.__doc__ = cls.__doc__\n view.__module__ = cls.__module__\n view.methods = cls.methods # type: ignore\n view.provide_automatic_options = cls.provide_automatic_options # type: ignore\n return view"},{"col":0,"comment":"Get the Flask app's logger and configure it if needed.\n\n The logger name will be the same as\n :attr:`app.import_name `.\n\n When :attr:`~flask.Flask.debug` is enabled, set the logger level to\n :data:`logging.DEBUG` if it is not set.\n\n If there is no handler for the logger's effective level, add a\n :class:`~logging.StreamHandler` for\n :func:`~flask.logging.wsgi_errors_stream` with a basic format.\n ","endLoc":74,"header":"def create_logger(app: \"Flask\") -> logging.Logger","id":665,"name":"create_logger","nodeType":"Function","startLoc":53,"text":"def create_logger(app: \"Flask\") -> logging.Logger:\n \"\"\"Get the Flask app's logger and configure it if needed.\n\n The logger name will be the same as\n :attr:`app.import_name `.\n\n When :attr:`~flask.Flask.debug` is enabled, set the logger level to\n :data:`logging.DEBUG` if it is not set.\n\n If there is no handler for the logger's effective level, add a\n :class:`~logging.StreamHandler` for\n :func:`~flask.logging.wsgi_errors_stream` with a basic format.\n \"\"\"\n logger = logging.getLogger(app.name)\n\n if app.debug and not logger.level:\n logger.setLevel(logging.DEBUG)\n\n if not has_level_handler(logger):\n logger.addHandler(default_handler)\n\n return logger"},{"attributeType":"null","col":17,"comment":"null","endLoc":3,"id":671,"name":"t","nodeType":"Attribute","startLoc":3,"text":"t"},{"attributeType":"str | None","col":4,"comment":"null","endLoc":154,"id":672,"name":"default_mimetype","nodeType":"Attribute","startLoc":154,"text":"default_mimetype"},{"col":0,"comment":"null","endLoc":47,"header":"def test_before_render_template()","id":674,"name":"test_before_render_template","nodeType":"Function","startLoc":25,"text":"def test_before_render_template():\n app = flask.Flask(__name__)\n\n @app.route(\"/\")\n def index():\n return flask.render_template(\"simple_template.html\", whiskey=42)\n\n recorded = []\n\n def record(sender, template, context):\n context[\"whiskey\"] = 43\n recorded.append((template, context))\n\n flask.before_render_template.connect(record, app)\n try:\n rv = app.test_client().get(\"/\")\n assert len(recorded) == 1\n template, context = recorded[0]\n assert template.name == \"simple_template.html\"\n assert context[\"whiskey\"] == 43\n assert rv.data == b\"

43

\"\n finally:\n flask.before_render_template.disconnect(record, app)"},{"attributeType":"null","col":0,"comment":"null","endLoc":9,"id":676,"name":"_signals","nodeType":"Attribute","startLoc":9,"text":"_signals"},{"col":4,"comment":"null","endLoc":96,"header":"@property\n def __class__(self) -> type[Self]","id":677,"name":"__class__","nodeType":"Function","startLoc":95,"text":"@property\n def __class__(self) -> type[Self]: ..."},{"col":4,"comment":"null","endLoc":99,"header":"@__class__.setter\n def __class__(self, __type: type[object]) -> None","id":679,"name":"__class__","nodeType":"Function","startLoc":98,"text":"@__class__.setter\n def __class__(self, __type: type[object]) -> None: ... # noqa: F811"},{"col":4,"comment":"null","endLoc":100,"header":"def __init__(self) -> None","id":680,"name":"__init__","nodeType":"Function","startLoc":100,"text":"def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":101,"header":"def __new__(cls) -> Self","id":682,"name":"__new__","nodeType":"Function","startLoc":101,"text":"def __new__(cls) -> Self: ..."},{"col":4,"comment":"null","endLoc":104,"header":"def __setattr__(self, __name: str, __value: Any) -> None","id":683,"name":"__setattr__","nodeType":"Function","startLoc":104,"text":"def __setattr__(self, __name: str, __value: Any) -> None: ..."},{"col":4,"comment":"null","endLoc":105,"header":"def __delattr__(self, __name: str) -> None","id":684,"name":"__delattr__","nodeType":"Function","startLoc":105,"text":"def __delattr__(self, __name: str) -> None: ..."},{"col":4,"comment":"null","endLoc":106,"header":"def __eq__(self, __value: object) -> bool","id":685,"name":"__eq__","nodeType":"Function","startLoc":106,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":107,"header":"def __ne__(self, __value: object) -> bool","id":686,"name":"__ne__","nodeType":"Function","startLoc":107,"text":"def __ne__(self, __value: object) -> bool: ..."},{"col":0,"comment":"null","endLoc":13,"header":"def no_app()","id":687,"name":"no_app","nodeType":"Function","startLoc":12,"text":"def no_app():\n pass"},{"col":4,"comment":"null","endLoc":108,"header":"def __str__(self) -> str","id":688,"name":"__str__","nodeType":"Function","startLoc":108,"text":"def __str__(self) -> str: ... # noqa: Y029"},{"col":4,"comment":"null","endLoc":109,"header":"def __repr__(self) -> str","id":689,"name":"__repr__","nodeType":"Function","startLoc":109,"text":"def __repr__(self) -> str: ... # noqa: Y029"},{"col":4,"comment":"null","endLoc":110,"header":"def __hash__(self) -> int","id":691,"name":"__hash__","nodeType":"Function","startLoc":110,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":111,"header":"def __format__(self, __format_spec: str) -> str","id":692,"name":"__format__","nodeType":"Function","startLoc":111,"text":"def __format__(self, __format_spec: str) -> str: ..."},{"col":4,"comment":"null","endLoc":112,"header":"def __getattribute__(self, __name: str) -> Any","id":693,"name":"__getattribute__","nodeType":"Function","startLoc":112,"text":"def __getattribute__(self, __name: str) -> Any: ..."},{"col":4,"comment":"null","endLoc":113,"header":"def __sizeof__(self) -> int","id":694,"name":"__sizeof__","nodeType":"Function","startLoc":113,"text":"def __sizeof__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":116,"header":"def __reduce__(self) -> str | tuple[Any, ...]","id":695,"name":"__reduce__","nodeType":"Function","startLoc":116,"text":"def __reduce__(self) -> str | tuple[Any, ...]: ..."},{"col":8,"comment":"null","endLoc":118,"header":"def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]","id":696,"name":"__reduce_ex__","nodeType":"Function","startLoc":118,"text":"def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ..."},{"col":4,"comment":"null","endLoc":1102,"header":"@overload\n def get(self, __key: _KT, __default: _VT) -> _VT","id":697,"name":"get","nodeType":"Function","startLoc":1101,"text":"@overload\n def get(self, __key: _KT, __default: _VT) -> _VT: ..."},{"id":698,"name":"pyproject.toml","nodeType":"TextFile","path":"examples/tutorial","text":"[project]\nname = \"flaskr\"\nversion = \"1.0.0\"\ndescription = \"The basic blog app built in the Flask tutorial.\"\nreadme = \"README.rst\"\nlicense = {text = \"BSD-3-Clause\"}\nmaintainers = [{name = \"Pallets\", email = \"contact@palletsprojects.com\"}]\ndependencies = [\n \"flask\",\n]\n\n[project.urls]\nDocumentation = \"https://flask.palletsprojects.com/tutorial/\"\n\n[project.optional-dependencies]\ntest = [\"pytest\"]\n\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\nfilterwarnings = [\"error\"]\n\n[tool.coverage.run]\nbranch = true\nsource = [\"flaskr\", \"tests\"]\n"},{"col":8,"comment":"null","endLoc":120,"header":"def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]","id":699,"name":"__reduce_ex__","nodeType":"Function","startLoc":120,"text":"def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ..."},{"col":4,"comment":"null","endLoc":1104,"header":"@overload\n def get(self, __key: _KT, __default: _T) -> _VT | _T","id":700,"name":"get","nodeType":"Function","startLoc":1103,"text":"@overload\n def get(self, __key: _KT, __default: _T) -> _VT | _T: ..."},{"col":8,"comment":"null","endLoc":122,"header":"def __getstate__(self) -> object","id":701,"name":"__getstate__","nodeType":"Function","startLoc":122,"text":"def __getstate__(self) -> object: ..."},{"col":4,"comment":"null","endLoc":124,"header":"def __dir__(self) -> Iterable[str]","id":702,"name":"__dir__","nodeType":"Function","startLoc":124,"text":"def __dir__(self) -> Iterable[str]: ..."},{"col":4,"comment":"null","endLoc":125,"header":"def __init_subclass__(cls) -> None","id":703,"name":"__init_subclass__","nodeType":"Function","startLoc":125,"text":"def __init_subclass__(cls) -> None: ..."},{"col":4,"comment":"null","endLoc":127,"header":"@classmethod\n def __subclasshook__(cls, __subclass: type) -> bool","id":704,"name":"__subclasshook__","nodeType":"Function","startLoc":126,"text":"@classmethod\n def __subclasshook__(cls, __subclass: type) -> bool: ..."},{"attributeType":"str | None","col":4,"comment":"null","endLoc":91,"id":705,"name":"__doc__","nodeType":"Attribute","startLoc":91,"text":"__doc__"},{"attributeType":"null","col":0,"comment":"null","endLoc":11,"id":706,"name":"template_rendered","nodeType":"Attribute","startLoc":11,"text":"template_rendered"},{"col":4,"comment":"null","endLoc":224,"header":"@overload\n def __new__(cls, __x: ConvertibleToInt = ...) -> Self","id":708,"name":"__new__","nodeType":"Function","startLoc":223,"text":"@overload\n def __new__(cls, __x: ConvertibleToInt = ...) -> Self: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":12,"id":709,"name":"before_render_template","nodeType":"Attribute","startLoc":12,"text":"before_render_template"},{"col":4,"comment":"null","endLoc":226,"header":"@overload\n def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> Self","id":710,"name":"__new__","nodeType":"Function","startLoc":225,"text":"@overload\n def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ..."},{"col":8,"comment":"null","endLoc":228,"header":"def as_integer_ratio(self) -> tuple[int, Literal[1]]","id":711,"name":"as_integer_ratio","nodeType":"Function","startLoc":228,"text":"def as_integer_ratio(self) -> tuple[int, Literal[1]]: ..."},{"col":4,"comment":"null","endLoc":231,"header":"@property\n def real(self) -> int","id":712,"name":"real","nodeType":"Function","startLoc":230,"text":"@property\n def real(self) -> int: ..."},{"col":4,"comment":"null","endLoc":233,"header":"@property\n def imag(self) -> Literal[0]","id":713,"name":"imag","nodeType":"Function","startLoc":232,"text":"@property\n def imag(self) -> Literal[0]: ..."},{"col":4,"comment":"null","endLoc":235,"header":"@property\n def numerator(self) -> int","id":714,"name":"numerator","nodeType":"Function","startLoc":234,"text":"@property\n def numerator(self) -> int: ..."},{"col":4,"comment":"null","endLoc":237,"header":"@property\n def denominator(self) -> Literal[1]","id":715,"name":"denominator","nodeType":"Function","startLoc":236,"text":"@property\n def denominator(self) -> Literal[1]: ..."},{"col":4,"comment":"null","endLoc":238,"header":"def conjugate(self) -> int","id":716,"name":"conjugate","nodeType":"Function","startLoc":238,"text":"def conjugate(self) -> int: ..."},{"col":4,"comment":"null","endLoc":239,"header":"def bit_length(self) -> int","id":717,"name":"bit_length","nodeType":"Function","startLoc":239,"text":"def bit_length(self) -> int: ..."},{"col":8,"comment":"null","endLoc":241,"header":"def bit_count(self) -> int","id":718,"name":"bit_count","nodeType":"Function","startLoc":241,"text":"def bit_count(self) -> int: ..."},{"col":8,"comment":"null","endLoc":246,"header":"def to_bytes(\n self, length: SupportsIndex = 1, byteorder: Literal[\"little\", \"big\"] = \"big\", *, signed: bool = False\n ) -> bytes","id":719,"name":"to_bytes","nodeType":"Function","startLoc":244,"text":"def to_bytes(\n self, length: SupportsIndex = 1, byteorder: Literal[\"little\", \"big\"] = \"big\", *, signed: bool = False\n ) -> bytes: ..."},{"col":8,"comment":"null","endLoc":256,"header":"def to_bytes(self, length: SupportsIndex, byteorder: Literal[\"little\", \"big\"], *, signed: bool = False) -> bytes","id":720,"name":"to_bytes","nodeType":"Function","startLoc":256,"text":"def to_bytes(self, length: SupportsIndex, byteorder: Literal[\"little\", \"big\"], *, signed: bool = False) -> bytes: ..."},{"col":0,"comment":"null","endLoc":21,"header":"def test_suppressed_exception_logging()","id":721,"name":"test_suppressed_exception_logging","nodeType":"Function","startLoc":6,"text":"def test_suppressed_exception_logging():\n class SuppressedFlask(flask.Flask):\n def log_exception(self, exc_info):\n pass\n\n out = StringIO()\n app = SuppressedFlask(__name__)\n\n @app.route(\"/\")\n def index():\n raise Exception(\"test\")\n\n rv = app.test_client().get(\"/\", errors_stream=out)\n assert rv.status_code == 500\n assert b\"Internal Server Error\" in rv.data\n assert not out.getvalue()"},{"col":8,"comment":"null","endLoc":254,"header":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"] = \"big\",\n *,\n signed: bool = False,\n ) -> Self","id":722,"name":"from_bytes","nodeType":"Function","startLoc":247,"text":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"] = \"big\",\n *,\n signed: bool = False,\n ) -> Self: ..."},{"col":8,"comment":"null","endLoc":254,"header":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"] = \"big\",\n *,\n signed: bool = False,\n ) -> Self","id":723,"name":"from_bytes","nodeType":"Function","startLoc":247,"text":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"] = \"big\",\n *,\n signed: bool = False,\n ) -> Self: ..."},{"col":8,"comment":"null","endLoc":264,"header":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"],\n *,\n signed: bool = False,\n ) -> Self","id":724,"name":"from_bytes","nodeType":"Function","startLoc":257,"text":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"],\n *,\n signed: bool = False,\n ) -> Self: ..."},{"col":8,"comment":"null","endLoc":264,"header":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"],\n *,\n signed: bool = False,\n ) -> Self","id":725,"name":"from_bytes","nodeType":"Function","startLoc":257,"text":"@classmethod\n def from_bytes(\n cls,\n bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n byteorder: Literal[\"little\", \"big\"],\n *,\n signed: bool = False,\n ) -> Self: ..."},{"attributeType":"BytesIO","col":8,"comment":"null","endLoc":27,"id":726,"name":"_io","nodeType":"Attribute","startLoc":27,"text":"self._io"},{"col":8,"comment":"null","endLoc":267,"header":"def is_integer(self) -> Literal[True]","id":727,"name":"is_integer","nodeType":"Function","startLoc":267,"text":"def is_integer(self) -> Literal[True]: ..."},{"col":8,"comment":"null","endLoc":267,"header":"def is_integer(self) -> Literal[True]","id":728,"name":"is_integer","nodeType":"Function","startLoc":267,"text":"def is_integer(self) -> Literal[True]: ..."},{"col":4,"comment":"null","endLoc":269,"header":"def __add__(self, __value: int) -> int","id":729,"name":"__add__","nodeType":"Function","startLoc":269,"text":"def __add__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":269,"header":"def __add__(self, __value: int) -> int","id":730,"name":"__add__","nodeType":"Function","startLoc":269,"text":"def __add__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":270,"header":"def __sub__(self, __value: int) -> int","id":731,"name":"__sub__","nodeType":"Function","startLoc":270,"text":"def __sub__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":270,"header":"def __sub__(self, __value: int) -> int","id":732,"name":"__sub__","nodeType":"Function","startLoc":270,"text":"def __sub__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":271,"header":"def __mul__(self, __value: int) -> int","id":733,"name":"__mul__","nodeType":"Function","startLoc":271,"text":"def __mul__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":271,"header":"def __mul__(self, __value: int) -> int","id":734,"name":"__mul__","nodeType":"Function","startLoc":271,"text":"def __mul__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":272,"header":"def __floordiv__(self, __value: int) -> int","id":735,"name":"__floordiv__","nodeType":"Function","startLoc":272,"text":"def __floordiv__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":272,"header":"def __floordiv__(self, __value: int) -> int","id":736,"name":"__floordiv__","nodeType":"Function","startLoc":272,"text":"def __floordiv__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":273,"header":"def __truediv__(self, __value: int) -> float","id":737,"name":"__truediv__","nodeType":"Function","startLoc":273,"text":"def __truediv__(self, __value: int) -> float: ..."},{"col":4,"comment":"null","endLoc":273,"header":"def __truediv__(self, __value: int) -> float","id":738,"name":"__truediv__","nodeType":"Function","startLoc":273,"text":"def __truediv__(self, __value: int) -> float: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":13,"id":739,"name":"request_started","nodeType":"Attribute","startLoc":13,"text":"request_started"},{"col":4,"comment":"null","endLoc":274,"header":"def __mod__(self, __value: int) -> int","id":740,"name":"__mod__","nodeType":"Function","startLoc":274,"text":"def __mod__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":274,"header":"def __mod__(self, __value: int) -> int","id":741,"name":"__mod__","nodeType":"Function","startLoc":274,"text":"def __mod__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":275,"header":"def __divmod__(self, __value: int) -> tuple[int, int]","id":742,"name":"__divmod__","nodeType":"Function","startLoc":275,"text":"def __divmod__(self, __value: int) -> tuple[int, int]: ..."},{"col":4,"comment":"null","endLoc":275,"header":"def __divmod__(self, __value: int) -> tuple[int, int]","id":743,"name":"__divmod__","nodeType":"Function","startLoc":275,"text":"def __divmod__(self, __value: int) -> tuple[int, int]: ..."},{"col":4,"comment":"null","endLoc":276,"header":"def __radd__(self, __value: int) -> int","id":744,"name":"__radd__","nodeType":"Function","startLoc":276,"text":"def __radd__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":276,"header":"def __radd__(self, __value: int) -> int","id":745,"name":"__radd__","nodeType":"Function","startLoc":276,"text":"def __radd__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":277,"header":"def __rsub__(self, __value: int) -> int","id":746,"name":"__rsub__","nodeType":"Function","startLoc":277,"text":"def __rsub__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":277,"header":"def __rsub__(self, __value: int) -> int","id":747,"name":"__rsub__","nodeType":"Function","startLoc":277,"text":"def __rsub__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":278,"header":"def __rmul__(self, __value: int) -> int","id":748,"name":"__rmul__","nodeType":"Function","startLoc":278,"text":"def __rmul__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":278,"header":"def __rmul__(self, __value: int) -> int","id":749,"name":"__rmul__","nodeType":"Function","startLoc":278,"text":"def __rmul__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":279,"header":"def __rfloordiv__(self, __value: int) -> int","id":750,"name":"__rfloordiv__","nodeType":"Function","startLoc":279,"text":"def __rfloordiv__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":279,"header":"def __rfloordiv__(self, __value: int) -> int","id":751,"name":"__rfloordiv__","nodeType":"Function","startLoc":279,"text":"def __rfloordiv__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":280,"header":"def __rtruediv__(self, __value: int) -> float","id":752,"name":"__rtruediv__","nodeType":"Function","startLoc":280,"text":"def __rtruediv__(self, __value: int) -> float: ..."},{"col":4,"comment":"null","endLoc":280,"header":"def __rtruediv__(self, __value: int) -> float","id":753,"name":"__rtruediv__","nodeType":"Function","startLoc":280,"text":"def __rtruediv__(self, __value: int) -> float: ..."},{"col":4,"comment":"null","endLoc":281,"header":"def __rmod__(self, __value: int) -> int","id":754,"name":"__rmod__","nodeType":"Function","startLoc":281,"text":"def __rmod__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":281,"header":"def __rmod__(self, __value: int) -> int","id":755,"name":"__rmod__","nodeType":"Function","startLoc":281,"text":"def __rmod__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":282,"header":"def __rdivmod__(self, __value: int) -> tuple[int, int]","id":756,"name":"__rdivmod__","nodeType":"Function","startLoc":282,"text":"def __rdivmod__(self, __value: int) -> tuple[int, int]: ..."},{"col":4,"comment":"null","endLoc":282,"header":"def __rdivmod__(self, __value: int) -> tuple[int, int]","id":757,"name":"__rdivmod__","nodeType":"Function","startLoc":282,"text":"def __rdivmod__(self, __value: int) -> tuple[int, int]: ..."},{"col":4,"comment":"null","endLoc":284,"header":"@overload\n def __pow__(self, __x: Literal[0]) -> Literal[1]","id":758,"name":"__pow__","nodeType":"Function","startLoc":283,"text":"@overload\n def __pow__(self, __x: Literal[0]) -> Literal[1]: ..."},{"col":4,"comment":"null","endLoc":284,"header":"@overload\n def __pow__(self, __x: Literal[0]) -> Literal[1]","id":759,"name":"__pow__","nodeType":"Function","startLoc":283,"text":"@overload\n def __pow__(self, __x: Literal[0]) -> Literal[1]: ..."},{"fileName":"test_session_interface.py","filePath":"tests","id":760,"nodeType":"File","text":"import flask\nfrom flask.globals import request_ctx\nfrom flask.sessions import SessionInterface\n\n\ndef test_open_session_with_endpoint():\n \"\"\"If request.endpoint (or other URL matching behavior) is needed\n while loading the session, RequestContext.match_request() can be\n called manually.\n \"\"\"\n\n class MySessionInterface(SessionInterface):\n def save_session(self, app, session, response):\n pass\n\n def open_session(self, app, request):\n request_ctx.match_request()\n assert request.endpoint is not None\n\n app = flask.Flask(__name__)\n app.session_interface = MySessionInterface()\n\n @app.get(\"/\")\n def index():\n return \"Hello, World!\"\n\n response = app.test_client().get(\"/\")\n assert response.status_code == 200\n"},{"col":4,"comment":"null","endLoc":286,"header":"@overload\n def __pow__(self, __value: Literal[0], __mod: None) -> Literal[1]","id":761,"name":"__pow__","nodeType":"Function","startLoc":285,"text":"@overload\n def __pow__(self, __value: Literal[0], __mod: None) -> Literal[1]: ..."},{"col":4,"comment":"null","endLoc":286,"header":"@overload\n def __pow__(self, __value: Literal[0], __mod: None) -> Literal[1]","id":762,"name":"__pow__","nodeType":"Function","startLoc":285,"text":"@overload\n def __pow__(self, __value: Literal[0], __mod: None) -> Literal[1]: ..."},{"col":4,"comment":"null","endLoc":288,"header":"@overload\n def __pow__(self, __value: _PositiveInteger, __mod: None = None) -> int","id":763,"name":"__pow__","nodeType":"Function","startLoc":287,"text":"@overload\n def __pow__(self, __value: _PositiveInteger, __mod: None = None) -> int: ..."},{"col":4,"comment":"null","endLoc":288,"header":"@overload\n def __pow__(self, __value: _PositiveInteger, __mod: None = None) -> int","id":764,"name":"__pow__","nodeType":"Function","startLoc":287,"text":"@overload\n def __pow__(self, __value: _PositiveInteger, __mod: None = None) -> int: ..."},{"col":4,"comment":"null","endLoc":290,"header":"@overload\n def __pow__(self, __value: _NegativeInteger, __mod: None = None) -> float","id":765,"name":"__pow__","nodeType":"Function","startLoc":289,"text":"@overload\n def __pow__(self, __value: _NegativeInteger, __mod: None = None) -> float: ..."},{"col":4,"comment":"null","endLoc":290,"header":"@overload\n def __pow__(self, __value: _NegativeInteger, __mod: None = None) -> float","id":766,"name":"__pow__","nodeType":"Function","startLoc":289,"text":"@overload\n def __pow__(self, __value: _NegativeInteger, __mod: None = None) -> float: ..."},{"col":4,"comment":"null","endLoc":294,"header":"@overload\n def __pow__(self, __value: int, __mod: None = None) -> Any","id":767,"name":"__pow__","nodeType":"Function","startLoc":293,"text":"@overload\n def __pow__(self, __value: int, __mod: None = None) -> Any: ..."},{"col":4,"comment":"null","endLoc":294,"header":"@overload\n def __pow__(self, __value: int, __mod: None = None) -> Any","id":768,"name":"__pow__","nodeType":"Function","startLoc":293,"text":"@overload\n def __pow__(self, __value: int, __mod: None = None) -> Any: ..."},{"col":4,"comment":"null","endLoc":296,"header":"@overload\n def __pow__(self, __value: int, __mod: int) -> int","id":769,"name":"__pow__","nodeType":"Function","startLoc":295,"text":"@overload\n def __pow__(self, __value: int, __mod: int) -> int: ..."},{"col":4,"comment":"null","endLoc":296,"header":"@overload\n def __pow__(self, __value: int, __mod: int) -> int","id":770,"name":"__pow__","nodeType":"Function","startLoc":295,"text":"@overload\n def __pow__(self, __value: int, __mod: int) -> int: ..."},{"col":4,"comment":"null","endLoc":297,"header":"def __rpow__(self, __value: int, __mod: int | None = None) -> Any","id":771,"name":"__rpow__","nodeType":"Function","startLoc":297,"text":"def __rpow__(self, __value: int, __mod: int | None = None) -> Any: ..."},{"col":4,"comment":"null","endLoc":297,"header":"def __rpow__(self, __value: int, __mod: int | None = None) -> Any","id":772,"name":"__rpow__","nodeType":"Function","startLoc":297,"text":"def __rpow__(self, __value: int, __mod: int | None = None) -> Any: ..."},{"col":0,"comment":"If request.endpoint (or other URL matching behavior) is needed\n while loading the session, RequestContext.match_request() can be\n called manually.\n ","endLoc":28,"header":"def test_open_session_with_endpoint()","id":773,"name":"test_open_session_with_endpoint","nodeType":"Function","startLoc":6,"text":"def test_open_session_with_endpoint():\n \"\"\"If request.endpoint (or other URL matching behavior) is needed\n while loading the session, RequestContext.match_request() can be\n called manually.\n \"\"\"\n\n class MySessionInterface(SessionInterface):\n def save_session(self, app, session, response):\n pass\n\n def open_session(self, app, request):\n request_ctx.match_request()\n assert request.endpoint is not None\n\n app = flask.Flask(__name__)\n app.session_interface = MySessionInterface()\n\n @app.get(\"/\")\n def index():\n return \"Hello, World!\"\n\n response = app.test_client().get(\"/\")\n assert response.status_code == 200"},{"col":4,"comment":"null","endLoc":298,"header":"def __and__(self, __value: int) -> int","id":774,"name":"__and__","nodeType":"Function","startLoc":298,"text":"def __and__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":298,"header":"def __and__(self, __value: int) -> int","id":775,"name":"__and__","nodeType":"Function","startLoc":298,"text":"def __and__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":299,"header":"def __or__(self, __value: int) -> int","id":776,"name":"__or__","nodeType":"Function","startLoc":299,"text":"def __or__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":299,"header":"def __or__(self, __value: int) -> int","id":777,"name":"__or__","nodeType":"Function","startLoc":299,"text":"def __or__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":300,"header":"def __xor__(self, __value: int) -> int","id":778,"name":"__xor__","nodeType":"Function","startLoc":300,"text":"def __xor__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":300,"header":"def __xor__(self, __value: int) -> int","id":779,"name":"__xor__","nodeType":"Function","startLoc":300,"text":"def __xor__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":301,"header":"def __lshift__(self, __value: int) -> int","id":780,"name":"__lshift__","nodeType":"Function","startLoc":301,"text":"def __lshift__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":301,"header":"def __lshift__(self, __value: int) -> int","id":781,"name":"__lshift__","nodeType":"Function","startLoc":301,"text":"def __lshift__(self, __value: int) -> int: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":14,"id":782,"name":"request_finished","nodeType":"Attribute","startLoc":14,"text":"request_finished"},{"col":4,"comment":"null","endLoc":302,"header":"def __rshift__(self, __value: int) -> int","id":783,"name":"__rshift__","nodeType":"Function","startLoc":302,"text":"def __rshift__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":302,"header":"def __rshift__(self, __value: int) -> int","id":784,"name":"__rshift__","nodeType":"Function","startLoc":302,"text":"def __rshift__(self, __value: int) -> int: ..."},{"attributeType":"datetime","col":4,"comment":"null","endLoc":231,"id":785,"name":"max","nodeType":"Attribute","startLoc":231,"text":"max"},{"col":4,"comment":"null","endLoc":303,"header":"def __rand__(self, __value: int) -> int","id":786,"name":"__rand__","nodeType":"Function","startLoc":303,"text":"def __rand__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":303,"header":"def __rand__(self, __value: int) -> int","id":787,"name":"__rand__","nodeType":"Function","startLoc":303,"text":"def __rand__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":304,"header":"def __ror__(self, __value: int) -> int","id":788,"name":"__ror__","nodeType":"Function","startLoc":304,"text":"def __ror__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":304,"header":"def __ror__(self, __value: int) -> int","id":789,"name":"__ror__","nodeType":"Function","startLoc":304,"text":"def __ror__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":305,"header":"def __rxor__(self, __value: int) -> int","id":790,"name":"__rxor__","nodeType":"Function","startLoc":305,"text":"def __rxor__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":305,"header":"def __rxor__(self, __value: int) -> int","id":791,"name":"__rxor__","nodeType":"Function","startLoc":305,"text":"def __rxor__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":306,"header":"def __rlshift__(self, __value: int) -> int","id":792,"name":"__rlshift__","nodeType":"Function","startLoc":306,"text":"def __rlshift__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":306,"header":"def __rlshift__(self, __value: int) -> int","id":793,"name":"__rlshift__","nodeType":"Function","startLoc":306,"text":"def __rlshift__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":307,"header":"def __rrshift__(self, __value: int) -> int","id":794,"name":"__rrshift__","nodeType":"Function","startLoc":307,"text":"def __rrshift__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":307,"header":"def __rrshift__(self, __value: int) -> int","id":795,"name":"__rrshift__","nodeType":"Function","startLoc":307,"text":"def __rrshift__(self, __value: int) -> int: ..."},{"col":4,"comment":"null","endLoc":308,"header":"def __neg__(self) -> int","id":796,"name":"__neg__","nodeType":"Function","startLoc":308,"text":"def __neg__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":308,"header":"def __neg__(self) -> int","id":797,"name":"__neg__","nodeType":"Function","startLoc":308,"text":"def __neg__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":309,"header":"def __pos__(self) -> int","id":798,"name":"__pos__","nodeType":"Function","startLoc":309,"text":"def __pos__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":309,"header":"def __pos__(self) -> int","id":799,"name":"__pos__","nodeType":"Function","startLoc":309,"text":"def __pos__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":310,"header":"def __invert__(self) -> int","id":800,"name":"__invert__","nodeType":"Function","startLoc":310,"text":"def __invert__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":310,"header":"def __invert__(self) -> int","id":801,"name":"__invert__","nodeType":"Function","startLoc":310,"text":"def __invert__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":311,"header":"def __trunc__(self) -> int","id":802,"name":"__trunc__","nodeType":"Function","startLoc":311,"text":"def __trunc__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":311,"header":"def __trunc__(self) -> int","id":803,"name":"__trunc__","nodeType":"Function","startLoc":311,"text":"def __trunc__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":312,"header":"def __ceil__(self) -> int","id":804,"name":"__ceil__","nodeType":"Function","startLoc":312,"text":"def __ceil__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":312,"header":"def __ceil__(self) -> int","id":805,"name":"__ceil__","nodeType":"Function","startLoc":312,"text":"def __ceil__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":313,"header":"def __floor__(self) -> int","id":806,"name":"__floor__","nodeType":"Function","startLoc":313,"text":"def __floor__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":313,"header":"def __floor__(self) -> int","id":807,"name":"__floor__","nodeType":"Function","startLoc":313,"text":"def __floor__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":314,"header":"def __round__(self, __ndigits: SupportsIndex = ...) -> int","id":808,"name":"__round__","nodeType":"Function","startLoc":314,"text":"def __round__(self, __ndigits: SupportsIndex = ...) -> int: ..."},{"col":4,"comment":"null","endLoc":314,"header":"def __round__(self, __ndigits: SupportsIndex = ...) -> int","id":809,"name":"__round__","nodeType":"Function","startLoc":314,"text":"def __round__(self, __ndigits: SupportsIndex = ...) -> int: ..."},{"col":4,"comment":"null","endLoc":315,"header":"def __getnewargs__(self) -> tuple[int]","id":810,"name":"__getnewargs__","nodeType":"Function","startLoc":315,"text":"def __getnewargs__(self) -> tuple[int]: ..."},{"col":4,"comment":"null","endLoc":315,"header":"def __getnewargs__(self) -> tuple[int]","id":811,"name":"__getnewargs__","nodeType":"Function","startLoc":315,"text":"def __getnewargs__(self) -> tuple[int]: ..."},{"col":4,"comment":"null","endLoc":316,"header":"def __eq__(self, __value: object) -> bool","id":812,"name":"__eq__","nodeType":"Function","startLoc":316,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":316,"header":"def __eq__(self, __value: object) -> bool","id":813,"name":"__eq__","nodeType":"Function","startLoc":316,"text":"def __eq__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":317,"header":"def __ne__(self, __value: object) -> bool","id":814,"name":"__ne__","nodeType":"Function","startLoc":317,"text":"def __ne__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":317,"header":"def __ne__(self, __value: object) -> bool","id":815,"name":"__ne__","nodeType":"Function","startLoc":317,"text":"def __ne__(self, __value: object) -> bool: ..."},{"col":4,"comment":"null","endLoc":318,"header":"def __lt__(self, __value: int) -> bool","id":816,"name":"__lt__","nodeType":"Function","startLoc":318,"text":"def __lt__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":318,"header":"def __lt__(self, __value: int) -> bool","id":817,"name":"__lt__","nodeType":"Function","startLoc":318,"text":"def __lt__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":319,"header":"def __le__(self, __value: int) -> bool","id":818,"name":"__le__","nodeType":"Function","startLoc":319,"text":"def __le__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":319,"header":"def __le__(self, __value: int) -> bool","id":819,"name":"__le__","nodeType":"Function","startLoc":319,"text":"def __le__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":320,"header":"def __gt__(self, __value: int) -> bool","id":820,"name":"__gt__","nodeType":"Function","startLoc":320,"text":"def __gt__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":320,"header":"def __gt__(self, __value: int) -> bool","id":821,"name":"__gt__","nodeType":"Function","startLoc":320,"text":"def __gt__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":321,"header":"def __ge__(self, __value: int) -> bool","id":822,"name":"__ge__","nodeType":"Function","startLoc":321,"text":"def __ge__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":321,"header":"def __ge__(self, __value: int) -> bool","id":823,"name":"__ge__","nodeType":"Function","startLoc":321,"text":"def __ge__(self, __value: int) -> bool: ..."},{"col":4,"comment":"null","endLoc":322,"header":"def __float__(self) -> float","id":824,"name":"__float__","nodeType":"Function","startLoc":322,"text":"def __float__(self) -> float: ..."},{"col":4,"comment":"null","endLoc":322,"header":"def __float__(self) -> float","id":825,"name":"__float__","nodeType":"Function","startLoc":322,"text":"def __float__(self) -> float: ..."},{"col":4,"comment":"null","endLoc":323,"header":"def __int__(self) -> int","id":826,"name":"__int__","nodeType":"Function","startLoc":323,"text":"def __int__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":323,"header":"def __int__(self) -> int","id":827,"name":"__int__","nodeType":"Function","startLoc":323,"text":"def __int__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":324,"header":"def __abs__(self) -> int","id":828,"name":"__abs__","nodeType":"Function","startLoc":324,"text":"def __abs__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":324,"header":"def __abs__(self) -> int","id":829,"name":"__abs__","nodeType":"Function","startLoc":324,"text":"def __abs__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":325,"header":"def __hash__(self) -> int","id":830,"name":"__hash__","nodeType":"Function","startLoc":325,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":325,"header":"def __hash__(self) -> int","id":831,"name":"__hash__","nodeType":"Function","startLoc":325,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":326,"header":"def __bool__(self) -> bool","id":832,"name":"__bool__","nodeType":"Function","startLoc":326,"text":"def __bool__(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":326,"header":"def __bool__(self) -> bool","id":833,"name":"__bool__","nodeType":"Function","startLoc":326,"text":"def __bool__(self) -> bool: ..."},{"col":4,"comment":"null","endLoc":327,"header":"def __index__(self) -> int","id":834,"name":"__index__","nodeType":"Function","startLoc":327,"text":"def __index__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":327,"header":"def __index__(self) -> int","id":835,"name":"__index__","nodeType":"Function","startLoc":327,"text":"def __index__(self) -> int: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":15,"id":836,"name":"request_tearing_down","nodeType":"Attribute","startLoc":15,"text":"request_tearing_down"},{"col":4,"comment":"null","endLoc":224,"header":"@_magic_enum_attr\n def value(self) -> int","id":837,"name":"value","nodeType":"Function","startLoc":223,"text":"@_magic_enum_attr\n def value(self) -> int: ..."},{"col":4,"comment":"null","endLoc":224,"header":"@_magic_enum_attr\n def value(self) -> int","id":838,"name":"value","nodeType":"Function","startLoc":223,"text":"@_magic_enum_attr\n def value(self) -> int: ..."},{"col":4,"comment":"null","endLoc":225,"header":"def __new__(cls, value: int) -> Self","id":839,"name":"__new__","nodeType":"Function","startLoc":225,"text":"def __new__(cls, value: int) -> Self: ..."},{"col":4,"comment":"null","endLoc":225,"header":"def __new__(cls, value: int) -> Self","id":840,"name":"__new__","nodeType":"Function","startLoc":225,"text":"def __new__(cls, value: int) -> Self: ..."},{"attributeType":"IntEnum","col":4,"comment":"null","endLoc":222,"id":841,"name":"_value_","nodeType":"Attribute","startLoc":222,"text":"_value_"},{"attributeType":"IntEnum","col":4,"comment":"null","endLoc":222,"id":842,"name":"_value_","nodeType":"Attribute","startLoc":222,"text":"_value_"},{"className":"timezone","col":0,"comment":"null","endLoc":39,"id":843,"nodeType":"Class","startLoc":29,"text":"@final\nclass timezone(tzinfo):\n utc: ClassVar[timezone]\n min: ClassVar[timezone]\n max: ClassVar[timezone]\n def __init__(self, offset: timedelta, name: str = ...) -> None: ...\n def tzname(self, __dt: datetime | None) -> str: ...\n def utcoffset(self, __dt: datetime | None) -> timedelta: ...\n def dst(self, __dt: datetime | None) -> None: ...\n def __hash__(self) -> int: ...\n def __eq__(self, __value: object) -> bool: ..."},{"className":"tzinfo","col":0,"comment":"null","endLoc":24,"id":844,"nodeType":"Class","startLoc":17,"text":"class tzinfo:\n @abstractmethod\n def tzname(self, __dt: datetime | None) -> str | None: ...\n @abstractmethod\n def utcoffset(self, __dt: datetime | None) -> timedelta | None: ...\n @abstractmethod\n def dst(self, __dt: datetime | None) -> timedelta | None: ...\n def fromutc(self, __dt: datetime) -> datetime: ..."},{"col":4,"comment":"null","endLoc":19,"header":"@abstractmethod\n def tzname(self, __dt: datetime | None) -> str | None","id":845,"name":"tzname","nodeType":"Function","startLoc":18,"text":"@abstractmethod\n def tzname(self, __dt: datetime | None) -> str | None: ..."},{"col":4,"comment":"null","endLoc":21,"header":"@abstractmethod\n def utcoffset(self, __dt: datetime | None) -> timedelta | None","id":846,"name":"utcoffset","nodeType":"Function","startLoc":20,"text":"@abstractmethod\n def utcoffset(self, __dt: datetime | None) -> timedelta | None: ..."},{"col":4,"comment":"null","endLoc":23,"header":"@abstractmethod\n def dst(self, __dt: datetime | None) -> timedelta | None","id":847,"name":"dst","nodeType":"Function","startLoc":22,"text":"@abstractmethod\n def dst(self, __dt: datetime | None) -> timedelta | None: ..."},{"col":4,"comment":"null","endLoc":24,"header":"def fromutc(self, __dt: datetime) -> datetime","id":848,"name":"fromutc","nodeType":"Function","startLoc":24,"text":"def fromutc(self, __dt: datetime) -> datetime: ..."},{"col":4,"comment":"null","endLoc":34,"header":"def __init__(self, offset: timedelta, name: str = ...) -> None","id":849,"name":"__init__","nodeType":"Function","startLoc":34,"text":"def __init__(self, offset: timedelta, name: str = ...) -> None: ..."},{"col":4,"comment":"null","endLoc":35,"header":"def tzname(self, __dt: datetime | None) -> str","id":850,"name":"tzname","nodeType":"Function","startLoc":35,"text":"def tzname(self, __dt: datetime | None) -> str: ..."},{"attributeType":"null","col":0,"comment":"null","endLoc":16,"id":851,"name":"got_request_exception","nodeType":"Attribute","startLoc":16,"text":"got_request_exception"},{"col":4,"comment":"null","endLoc":36,"header":"def utcoffset(self, __dt: datetime | None) -> timedelta","id":852,"name":"utcoffset","nodeType":"Function","startLoc":36,"text":"def utcoffset(self, __dt: datetime | None) -> timedelta: ..."},{"col":4,"comment":"null","endLoc":37,"header":"def dst(self, __dt: datetime | None) -> None","id":853,"name":"dst","nodeType":"Function","startLoc":37,"text":"def dst(self, __dt: datetime | None) -> None: ..."},{"col":4,"comment":"null","endLoc":38,"header":"def __hash__(self) -> int","id":854,"name":"__hash__","nodeType":"Function","startLoc":38,"text":"def __hash__(self) -> int: ..."},{"col":4,"comment":"null","endLoc":39,"header":"def __eq__(self, __value: object) -> bool","id":855,"name":"__eq__","nodeType":"Function","startLoc":39,"text":"def __eq__(self, __value: object) -> bool: ..."},{"attributeType":"timezone","col":4,"comment":"null","endLoc":31,"id":856,"name":"utc","nodeType":"Attribute","startLoc":31,"text":"utc"},{"col":0,"comment":"null","endLoc":92,"header":"def test_request_signals()","id":857,"name":"test_request_signals","nodeType":"Function","startLoc":50,"text":"def test_request_signals():\n app = flask.Flask(__name__)\n calls = []\n\n def before_request_signal(sender):\n calls.append(\"before-signal\")\n\n def after_request_signal(sender, response):\n assert response.data == b\"stuff\"\n calls.append(\"after-signal\")\n\n @app.before_request\n def before_request_handler():\n calls.append(\"before-handler\")\n\n @app.after_request\n def after_request_handler(response):\n calls.append(\"after-handler\")\n response.data = \"stuff\"\n return response\n\n @app.route(\"/\")\n def index():\n calls.append(\"handler\")\n return \"ignored anyway\"\n\n flask.request_started.connect(before_request_signal, app)\n flask.request_finished.connect(after_request_signal, app)\n\n try:\n rv = app.test_client().get(\"/\")\n assert rv.data == b\"stuff\"\n\n assert calls == [\n \"before-signal\",\n \"before-handler\",\n \"handler\",\n \"after-handler\",\n \"after-signal\",\n ]\n finally:\n flask.request_started.disconnect(before_request_signal, app)\n flask.request_finished.disconnect(after_request_signal, app)"},{"className":"TestRoutes","col":0,"comment":"null","endLoc":499,"id":858,"nodeType":"Class","startLoc":432,"text":"class TestRoutes:\n @pytest.fixture\n def app(self):\n app = Flask(__name__)\n app.testing = True\n\n @app.route(\"/get_post//\", methods=[\"GET\", \"POST\"])\n def yyy_get_post(x, y):\n pass\n\n @app.route(\"/zzz_post\", methods=[\"POST\"])\n def aaa_post():\n pass\n\n return app\n\n @pytest.fixture\n def invoke(self, app, runner):\n cli = FlaskGroup(create_app=lambda: app)\n return partial(runner.invoke, cli)\n\n @pytest.fixture\n def invoke_no_routes(self, runner):\n def create_app():\n app = Flask(__name__, static_folder=None)\n app.testing = True\n\n return app\n\n cli = FlaskGroup(create_app=create_app)\n return partial(runner.invoke, cli)\n\n def expect_order(self, order, output):\n # skip the header and match the start of each row\n for expect, line in zip(order, output.splitlines()[2:]):\n # do this instead of startswith for nicer pytest output\n assert line[: len(expect)] == expect\n\n def test_simple(self, invoke):\n result = invoke([\"routes\"])\n assert result.exit_code == 0\n self.expect_order([\"aaa_post\", \"static\", \"yyy_get_post\"], result.output)\n\n def test_sort(self, app, invoke):\n default_output = invoke([\"routes\"]).output\n endpoint_output = invoke([\"routes\", \"-s\", \"endpoint\"]).output\n assert default_output == endpoint_output\n self.expect_order(\n [\"static\", \"yyy_get_post\", \"aaa_post\"],\n invoke([\"routes\", \"-s\", \"methods\"]).output,\n )\n self.expect_order(\n [\"yyy_get_post\", \"static\", \"aaa_post\"],\n invoke([\"routes\", \"-s\", \"rule\"]).output,\n )\n match_order = [r.endpoint for r in app.url_map.iter_rules()]\n self.expect_order(match_order, invoke([\"routes\", \"-s\", \"match\"]).output)\n\n def test_all_methods(self, invoke):\n output = invoke([\"routes\"]).output\n assert \"GET, HEAD, OPTIONS, POST\" not in output\n output = invoke([\"routes\", \"--all-methods\"]).output\n assert \"GET, HEAD, OPTIONS, POST\" in output\n\n def test_no_routes(self, invoke_no_routes):\n result = invoke_no_routes([\"routes\"])\n assert result.exit_code == 0\n assert \"No routes were registered.\" in result.output"},{"col":4,"comment":"null","endLoc":446,"header":"@pytest.fixture\n def app(self)","id":859,"name":"app","nodeType":"Function","startLoc":433,"text":"@pytest.fixture\n def app(self):\n app = Flask(__name__)\n app.testing = True\n\n @app.route(\"/get_post//\", methods=[\"GET\", \"POST\"])\n def yyy_get_post(x, y):\n pass\n\n @app.route(\"/zzz_post\", methods=[\"POST\"])\n def aaa_post():\n pass\n\n return app"},{"attributeType":"null","col":0,"comment":"null","endLoc":17,"id":860,"name":"appcontext_tearing_down","nodeType":"Attribute","startLoc":17,"text":"appcontext_tearing_down"},{"attributeType":"null","col":0,"comment":"null","endLoc":18,"id":861,"name":"appcontext_pushed","nodeType":"Attribute","startLoc":18,"text":"appcontext_pushed"},{"col":4,"comment":"null","endLoc":15,"header":"@property\n def phrase(self) -> str","id":862,"name":"phrase","nodeType":"Function","startLoc":14,"text":"@property\n def phrase(self) -> str: ..."},{"col":4,"comment":"null","endLoc":15,"header":"@property\n def phrase(self) -> str","id":863,"name":"phrase","nodeType":"Function","startLoc":14,"text":"@property\n def phrase(self) -> str: ..."},{"col":4,"comment":"null","endLoc":17,"header":"@property\n def description(self) -> str","id":864,"name":"description","nodeType":"Function","startLoc":16,"text":"@property\n def description(self) -> str: ..."},{"col":4,"comment":"null","endLoc":17,"header":"@property\n def description(self) -> str","id":865,"name":"description","nodeType":"Function","startLoc":16,"text":"@property\n def description(self) -> str: ..."},{"col":8,"comment":"null","endLoc":84,"header":"@property\n def is_informational(self) -> bool","id":866,"name":"is_informational","nodeType":"Function","startLoc":83,"text":"@property\n def is_informational(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":84,"header":"@property\n def is_informational(self) -> bool","id":867,"name":"is_informational","nodeType":"Function","startLoc":83,"text":"@property\n def is_informational(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":86,"header":"@property\n def is_success(self) -> bool","id":868,"name":"is_success","nodeType":"Function","startLoc":85,"text":"@property\n def is_success(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":86,"header":"@property\n def is_success(self) -> bool","id":869,"name":"is_success","nodeType":"Function","startLoc":85,"text":"@property\n def is_success(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":88,"header":"@property\n def is_redirection(self) -> bool","id":870,"name":"is_redirection","nodeType":"Function","startLoc":87,"text":"@property\n def is_redirection(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":88,"header":"@property\n def is_redirection(self) -> bool","id":871,"name":"is_redirection","nodeType":"Function","startLoc":87,"text":"@property\n def is_redirection(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":90,"header":"@property\n def is_client_error(self) -> bool","id":872,"name":"is_client_error","nodeType":"Function","startLoc":89,"text":"@property\n def is_client_error(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":90,"header":"@property\n def is_client_error(self) -> bool","id":873,"name":"is_client_error","nodeType":"Function","startLoc":89,"text":"@property\n def is_client_error(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":92,"header":"@property\n def is_server_error(self) -> bool","id":874,"name":"is_server_error","nodeType":"Function","startLoc":91,"text":"@property\n def is_server_error(self) -> bool: ..."},{"col":8,"comment":"null","endLoc":92,"header":"@property\n def is_server_error(self) -> bool","id":875,"name":"is_server_error","nodeType":"Function","startLoc":91,"text":"@property\n def is_server_error(self) -> bool: ..."},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":18,"id":876,"name":"CONTINUE","nodeType":"Attribute","startLoc":18,"text":"CONTINUE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":18,"id":877,"name":"CONTINUE","nodeType":"Attribute","startLoc":18,"text":"CONTINUE"},{"attributeType":"null","col":0,"comment":"null","endLoc":19,"id":879,"name":"appcontext_popped","nodeType":"Attribute","startLoc":19,"text":"appcontext_popped"},{"className":"TestSendfile","col":0,"comment":"null","endLoc":99,"id":880,"nodeType":"Class","startLoc":33,"text":"class TestSendfile:\n def test_send_file(self, app, req_ctx):\n rv = flask.send_file(\"static/index.html\")\n assert rv.direct_passthrough\n assert rv.mimetype == \"text/html\"\n\n with app.open_resource(\"static/index.html\") as f:\n rv.direct_passthrough = False\n assert rv.data == f.read()\n\n rv.close()\n\n def test_static_file(self, app, req_ctx):\n # Default max_age is None.\n\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age is None\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age is None\n rv.close()\n\n app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = 3600\n\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n # Test with pathlib.Path.\n rv = app.send_static_file(FakePath(\"index.html\"))\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n class StaticFileApp(flask.Flask):\n def get_send_file_max_age(self, filename):\n return 10\n\n app = StaticFileApp(__name__)\n\n with app.test_request_context():\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age == 10\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age == 10\n rv.close()\n\n def test_send_from_directory(self, app, req_ctx):\n app.root_path = os.path.join(\n os.path.dirname(__file__), \"test_apps\", \"subdomaintestmodule\"\n )\n rv = flask.send_from_directory(\"static\", \"hello.txt\")\n rv.direct_passthrough = False\n assert rv.data.strip() == b\"Hello Subdomain\"\n rv.close()"},{"col":4,"comment":"null","endLoc":43,"header":"def test_send_file(self, app, req_ctx)","id":881,"name":"test_send_file","nodeType":"Function","startLoc":34,"text":"def test_send_file(self, app, req_ctx):\n rv = flask.send_file(\"static/index.html\")\n assert rv.direct_passthrough\n assert rv.mimetype == \"text/html\"\n\n with app.open_resource(\"static/index.html\") as f:\n rv.direct_passthrough = False\n assert rv.data == f.read()\n\n rv.close()"},{"col":4,"comment":"null","endLoc":451,"header":"@pytest.fixture\n def invoke(self, app, runner)","id":882,"name":"invoke","nodeType":"Function","startLoc":448,"text":"@pytest.fixture\n def invoke(self, app, runner):\n cli = FlaskGroup(create_app=lambda: app)\n return partial(runner.invoke, cli)"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":19,"id":883,"name":"SWITCHING_PROTOCOLS","nodeType":"Attribute","startLoc":19,"text":"SWITCHING_PROTOCOLS"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":20,"id":884,"name":"PROCESSING","nodeType":"Attribute","startLoc":20,"text":"PROCESSING"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":21,"id":885,"name":"OK","nodeType":"Attribute","startLoc":21,"text":"OK"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":22,"id":886,"name":"CREATED","nodeType":"Attribute","startLoc":22,"text":"CREATED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":23,"id":887,"name":"ACCEPTED","nodeType":"Attribute","startLoc":23,"text":"ACCEPTED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":24,"id":888,"name":"NON_AUTHORITATIVE_INFORMATION","nodeType":"Attribute","startLoc":24,"text":"NON_AUTHORITATIVE_INFORMATION"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":25,"id":889,"name":"NO_CONTENT","nodeType":"Attribute","startLoc":25,"text":"NO_CONTENT"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":26,"id":890,"name":"RESET_CONTENT","nodeType":"Attribute","startLoc":26,"text":"RESET_CONTENT"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":27,"id":891,"name":"PARTIAL_CONTENT","nodeType":"Attribute","startLoc":27,"text":"PARTIAL_CONTENT"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":28,"id":892,"name":"MULTI_STATUS","nodeType":"Attribute","startLoc":28,"text":"MULTI_STATUS"},{"col":36,"endLoc":450,"id":893,"nodeType":"Lambda","startLoc":450,"text":"lambda: app"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":29,"id":894,"name":"ALREADY_REPORTED","nodeType":"Attribute","startLoc":29,"text":"ALREADY_REPORTED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":30,"id":895,"name":"IM_USED","nodeType":"Attribute","startLoc":30,"text":"IM_USED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":31,"id":896,"name":"MULTIPLE_CHOICES","nodeType":"Attribute","startLoc":31,"text":"MULTIPLE_CHOICES"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":32,"id":897,"name":"MOVED_PERMANENTLY","nodeType":"Attribute","startLoc":32,"text":"MOVED_PERMANENTLY"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":33,"id":898,"name":"FOUND","nodeType":"Attribute","startLoc":33,"text":"FOUND"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":34,"id":899,"name":"SEE_OTHER","nodeType":"Attribute","startLoc":34,"text":"SEE_OTHER"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":35,"id":900,"name":"NOT_MODIFIED","nodeType":"Attribute","startLoc":35,"text":"NOT_MODIFIED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":36,"id":901,"name":"USE_PROXY","nodeType":"Attribute","startLoc":36,"text":"USE_PROXY"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":37,"id":902,"name":"TEMPORARY_REDIRECT","nodeType":"Attribute","startLoc":37,"text":"TEMPORARY_REDIRECT"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":38,"id":903,"name":"PERMANENT_REDIRECT","nodeType":"Attribute","startLoc":38,"text":"PERMANENT_REDIRECT"},{"attributeType":"null","col":0,"comment":"null","endLoc":20,"id":904,"name":"message_flashed","nodeType":"Attribute","startLoc":20,"text":"message_flashed"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":39,"id":905,"name":"BAD_REQUEST","nodeType":"Attribute","startLoc":39,"text":"BAD_REQUEST"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":40,"id":906,"name":"UNAUTHORIZED","nodeType":"Attribute","startLoc":40,"text":"UNAUTHORIZED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":41,"id":907,"name":"PAYMENT_REQUIRED","nodeType":"Attribute","startLoc":41,"text":"PAYMENT_REQUIRED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":42,"id":908,"name":"FORBIDDEN","nodeType":"Attribute","startLoc":42,"text":"FORBIDDEN"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":43,"id":909,"name":"NOT_FOUND","nodeType":"Attribute","startLoc":43,"text":"NOT_FOUND"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":44,"id":910,"name":"METHOD_NOT_ALLOWED","nodeType":"Attribute","startLoc":44,"text":"METHOD_NOT_ALLOWED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":45,"id":911,"name":"NOT_ACCEPTABLE","nodeType":"Attribute","startLoc":45,"text":"NOT_ACCEPTABLE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":46,"id":912,"name":"PROXY_AUTHENTICATION_REQUIRED","nodeType":"Attribute","startLoc":46,"text":"PROXY_AUTHENTICATION_REQUIRED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":47,"id":913,"name":"REQUEST_TIMEOUT","nodeType":"Attribute","startLoc":47,"text":"REQUEST_TIMEOUT"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":48,"id":914,"name":"CONFLICT","nodeType":"Attribute","startLoc":48,"text":"CONFLICT"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":49,"id":915,"name":"GONE","nodeType":"Attribute","startLoc":49,"text":"GONE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":50,"id":916,"name":"LENGTH_REQUIRED","nodeType":"Attribute","startLoc":50,"text":"LENGTH_REQUIRED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":51,"id":917,"name":"PRECONDITION_FAILED","nodeType":"Attribute","startLoc":51,"text":"PRECONDITION_FAILED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":52,"id":918,"name":"REQUEST_ENTITY_TOO_LARGE","nodeType":"Attribute","startLoc":52,"text":"REQUEST_ENTITY_TOO_LARGE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":53,"id":919,"name":"REQUEST_URI_TOO_LONG","nodeType":"Attribute","startLoc":53,"text":"REQUEST_URI_TOO_LONG"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":54,"id":920,"name":"UNSUPPORTED_MEDIA_TYPE","nodeType":"Attribute","startLoc":54,"text":"UNSUPPORTED_MEDIA_TYPE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":55,"id":921,"name":"REQUESTED_RANGE_NOT_SATISFIABLE","nodeType":"Attribute","startLoc":55,"text":"REQUESTED_RANGE_NOT_SATISFIABLE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":56,"id":922,"name":"EXPECTATION_FAILED","nodeType":"Attribute","startLoc":56,"text":"EXPECTATION_FAILED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":57,"id":923,"name":"UNPROCESSABLE_ENTITY","nodeType":"Attribute","startLoc":57,"text":"UNPROCESSABLE_ENTITY"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":58,"id":924,"name":"LOCKED","nodeType":"Attribute","startLoc":58,"text":"LOCKED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":59,"id":925,"name":"FAILED_DEPENDENCY","nodeType":"Attribute","startLoc":59,"text":"FAILED_DEPENDENCY"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":60,"id":926,"name":"UPGRADE_REQUIRED","nodeType":"Attribute","startLoc":60,"text":"UPGRADE_REQUIRED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":61,"id":927,"name":"PRECONDITION_REQUIRED","nodeType":"Attribute","startLoc":61,"text":"PRECONDITION_REQUIRED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":62,"id":928,"name":"TOO_MANY_REQUESTS","nodeType":"Attribute","startLoc":62,"text":"TOO_MANY_REQUESTS"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":63,"id":929,"name":"REQUEST_HEADER_FIELDS_TOO_LARGE","nodeType":"Attribute","startLoc":63,"text":"REQUEST_HEADER_FIELDS_TOO_LARGE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":64,"id":930,"name":"INTERNAL_SERVER_ERROR","nodeType":"Attribute","startLoc":64,"text":"INTERNAL_SERVER_ERROR"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":65,"id":931,"name":"NOT_IMPLEMENTED","nodeType":"Attribute","startLoc":65,"text":"NOT_IMPLEMENTED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":66,"id":932,"name":"BAD_GATEWAY","nodeType":"Attribute","startLoc":66,"text":"BAD_GATEWAY"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":67,"id":933,"name":"SERVICE_UNAVAILABLE","nodeType":"Attribute","startLoc":67,"text":"SERVICE_UNAVAILABLE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":68,"id":934,"name":"GATEWAY_TIMEOUT","nodeType":"Attribute","startLoc":68,"text":"GATEWAY_TIMEOUT"},{"col":0,"comment":"","endLoc":1,"header":"signals.py#","id":935,"name":"","nodeType":"Function","startLoc":1,"text":"_signals = Namespace()\n\ntemplate_rendered = _signals.signal(\"template-rendered\")\n\nbefore_render_template = _signals.signal(\"before-render-template\")\n\nrequest_started = _signals.signal(\"request-started\")\n\nrequest_finished = _signals.signal(\"request-finished\")\n\nrequest_tearing_down = _signals.signal(\"request-tearing-down\")\n\ngot_request_exception = _signals.signal(\"got-request-exception\")\n\nappcontext_tearing_down = _signals.signal(\"appcontext-tearing-down\")\n\nappcontext_pushed = _signals.signal(\"appcontext-pushed\")\n\nappcontext_popped = _signals.signal(\"appcontext-popped\")\n\nmessage_flashed = _signals.signal(\"message-flashed\")"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":69,"id":936,"name":"HTTP_VERSION_NOT_SUPPORTED","nodeType":"Attribute","startLoc":69,"text":"HTTP_VERSION_NOT_SUPPORTED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":70,"id":937,"name":"VARIANT_ALSO_NEGOTIATES","nodeType":"Attribute","startLoc":70,"text":"VARIANT_ALSO_NEGOTIATES"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":71,"id":938,"name":"INSUFFICIENT_STORAGE","nodeType":"Attribute","startLoc":71,"text":"INSUFFICIENT_STORAGE"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":72,"id":939,"name":"LOOP_DETECTED","nodeType":"Attribute","startLoc":72,"text":"LOOP_DETECTED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":73,"id":940,"name":"NOT_EXTENDED","nodeType":"Attribute","startLoc":73,"text":"NOT_EXTENDED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":74,"id":941,"name":"NETWORK_AUTHENTICATION_REQUIRED","nodeType":"Attribute","startLoc":74,"text":"NETWORK_AUTHENTICATION_REQUIRED"},{"attributeType":"HTTPStatus","col":4,"comment":"null","endLoc":75,"id":942,"name":"MISDIRECTED_REQUEST","nodeType":"Attribute","startLoc":75,"text":"MISDIRECTED_REQUEST"},{"id":943,"name":"appdispatch.rst","nodeType":"TextFile","path":"docs/patterns","text":"Application Dispatching\n=======================\n\nApplication dispatching is the process of combining multiple Flask\napplications on the WSGI level. You can combine not only Flask\napplications but any WSGI application. This would allow you to run a\nDjango and a Flask application in the same interpreter side by side if\nyou want. The usefulness of this depends on how the applications work\ninternally.\n\nThe fundamental difference from :doc:`packages` is that in this case you\nare running the same or different Flask applications that are entirely\nisolated from each other. They run different configurations and are\ndispatched on the WSGI level.\n\n\nWorking with this Document\n--------------------------\n\nEach of the techniques and examples below results in an ``application``\nobject that can be run with any WSGI server. For production, see\n:doc:`/deploying/index`. For development, Werkzeug provides a server\nthrough :func:`werkzeug.serving.run_simple`::\n\n from werkzeug.serving import run_simple\n run_simple('localhost', 5000, application, use_reloader=True)\n\nNote that :func:`run_simple ` is not intended for\nuse in production. Use a production WSGI server. See :doc:`/deploying/index`.\n\nIn order to use the interactive debugger, debugging must be enabled both on\nthe application and the simple server. Here is the \"hello world\" example with\ndebugging and :func:`run_simple `::\n\n from flask import Flask\n from werkzeug.serving import run_simple\n\n app = Flask(__name__)\n app.debug = True\n\n @app.route('/')\n def hello_world():\n return 'Hello World!'\n\n if __name__ == '__main__':\n run_simple('localhost', 5000, app,\n use_reloader=True, use_debugger=True, use_evalex=True)\n\n\nCombining Applications\n----------------------\n\nIf you have entirely separated applications and you want them to work next\nto each other in the same Python interpreter process you can take\nadvantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea\nhere is that each Flask application is a valid WSGI application and they\nare combined by the dispatcher middleware into a larger one that is\ndispatched based on prefix.\n\nFor example you could have your main application run on ``/`` and your\nbackend interface on ``/backend``::\n\n from werkzeug.middleware.dispatcher import DispatcherMiddleware\n from frontend_app import application as frontend\n from backend_app import application as backend\n\n application = DispatcherMiddleware(frontend, {\n '/backend': backend\n })\n\n\nDispatch by Subdomain\n---------------------\n\nSometimes you might want to use multiple instances of the same application\nwith different configurations. Assuming the application is created inside\na function and you can call that function to instantiate it, that is\nreally easy to implement. In order to develop your application to support\ncreating new instances in functions have a look at the\n:doc:`appfactories` pattern.\n\nA very common example would be creating applications per subdomain. For\ninstance you configure your webserver to dispatch all requests for all\nsubdomains to your application and you then use the subdomain information\nto create user-specific instances. Once you have your server set up to\nlisten on all subdomains you can use a very simple WSGI application to do\nthe dynamic application creation.\n\nThe perfect level for abstraction in that regard is the WSGI layer. You\nwrite your own WSGI application that looks at the request that comes and\ndelegates it to your Flask application. If that application does not\nexist yet, it is dynamically created and remembered::\n\n from threading import Lock\n\n class SubdomainDispatcher:\n\n def __init__(self, domain, create_app):\n self.domain = domain\n self.create_app = create_app\n self.lock = Lock()\n self.instances = {}\n\n def get_application(self, host):\n host = host.split(':')[0]\n assert host.endswith(self.domain), 'Configuration error'\n subdomain = host[:-len(self.domain)].rstrip('.')\n with self.lock:\n app = self.instances.get(subdomain)\n if app is None:\n app = self.create_app(subdomain)\n self.instances[subdomain] = app\n return app\n\n def __call__(self, environ, start_response):\n app = self.get_application(environ['HTTP_HOST'])\n return app(environ, start_response)\n\n\nThis dispatcher can then be used like this::\n\n from myapplication import create_app, get_user_for_subdomain\n from werkzeug.exceptions import NotFound\n\n def make_app(subdomain):\n user = get_user_for_subdomain(subdomain)\n if user is None:\n # if there is no user for that subdomain we still have\n # to return a WSGI application that handles that request.\n # We can then just return the NotFound() exception as\n # application which will render a default 404 page.\n # You might also redirect the user to the main page then\n return NotFound()\n\n # otherwise create the application for the specific user\n return create_app(user)\n\n application = SubdomainDispatcher('example.com', make_app)\n\n\nDispatch by Path\n----------------\n\nDispatching by a path on the URL is very similar. Instead of looking at\nthe ``Host`` header to figure out the subdomain one simply looks at the\nrequest path up to the first slash::\n\n from threading import Lock\n from werkzeug.wsgi import pop_path_info, peek_path_info\n\n class PathDispatcher:\n\n def __init__(self, default_app, create_app):\n self.default_app = default_app\n self.create_app = create_app\n self.lock = Lock()\n self.instances = {}\n\n def get_application(self, prefix):\n with self.lock:\n app = self.instances.get(prefix)\n if app is None:\n app = self.create_app(prefix)\n if app is not None:\n self.instances[prefix] = app\n return app\n\n def __call__(self, environ, start_response):\n app = self.get_application(peek_path_info(environ))\n if app is not None:\n pop_path_info(environ)\n else:\n app = self.default_app\n return app(environ, start_response)\n\nThe big difference between this and the subdomain one is that this one\nfalls back to another application if the creator function returns ``None``::\n\n from myapplication import create_app, default_app, get_user_for_prefix\n\n def make_app(prefix):\n user = get_user_for_prefix(prefix)\n if user is not None:\n return create_app(user)\n\n application = PathDispatcher(default_app, make_app)\n"},{"attributeType":"timezone","col":4,"comment":"null","endLoc":32,"id":944,"name":"min","nodeType":"Attribute","startLoc":32,"text":"min"},{"attributeType":"timezone","col":4,"comment":"null","endLoc":33,"id":945,"name":"max","nodeType":"Attribute","startLoc":33,"text":"max"},{"col":4,"comment":"null","endLoc":90,"header":"def test_static_file(self, app, req_ctx)","id":946,"name":"test_static_file","nodeType":"Function","startLoc":45,"text":"def test_static_file(self, app, req_ctx):\n # Default max_age is None.\n\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age is None\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age is None\n rv.close()\n\n app.config[\"SEND_FILE_MAX_AGE_DEFAULT\"] = 3600\n\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n # Test with pathlib.Path.\n rv = app.send_static_file(FakePath(\"index.html\"))\n assert rv.cache_control.max_age == 3600\n rv.close()\n\n class StaticFileApp(flask.Flask):\n def get_send_file_max_age(self, filename):\n return 10\n\n app = StaticFileApp(__name__)\n\n with app.test_request_context():\n # Test with static file handler.\n rv = app.send_static_file(\"index.html\")\n assert rv.cache_control.max_age == 10\n rv.close()\n\n # Test with direct use of send_file.\n rv = flask.send_file(\"static/index.html\")\n assert rv.cache_control.max_age == 10\n rv.close()"},{"col":0,"comment":"null","endLoc":17,"header":"@app.errorhandler(400)\n@app.errorhandler(HTTPStatus.BAD_REQUEST)\n@app.errorhandler(BadRequest)\ndef handle_400(e","id":947,"name":"handle_400","nodeType":"Function","startLoc":13,"text":"@app.errorhandler(400)\n@app.errorhandler(HTTPStatus.BAD_REQUEST)\n@app.errorhandler(BadRequest)\ndef handle_400(e: BadRequest) -> str:\n return \"\""},{"id":949,"name":"LICENSE.rst","nodeType":"TextFile","path":"examples/tutorial","text":"Copyright 2010 Pallets\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\nTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"},{"id":950,"name":"README.rst","nodeType":"TextFile","path":"examples/tutorial","text":"Flaskr\n======\n\nThe basic blog app built in the Flask `tutorial`_.\n\n.. _tutorial: https://flask.palletsprojects.com/tutorial/\n\n\nInstall\n-------\n\n**Be sure to use the same version of the code as the version of the docs\nyou're reading.** You probably want the latest tagged version, but the\ndefault Git version is the main branch. ::\n\n # clone the repository\n $ git clone https://github.com/pallets/flask\n $ cd flask\n # checkout the correct version\n $ git tag # shows the tagged versions\n $ git checkout latest-tag-found-above\n $ cd examples/tutorial\n\nCreate a virtualenv and activate it::\n\n $ python3 -m venv .venv\n $ . .venv/bin/activate\n\nOr on Windows cmd::\n\n $ py -3 -m venv .venv\n $ .venv\\Scripts\\activate.bat\n\nInstall Flaskr::\n\n $ pip install -e .\n\nOr if you are using the main branch, install Flask from source before\ninstalling Flaskr::\n\n $ pip install -e ../..\n $ pip install -e .\n\n\nRun\n---\n\n.. code-block:: text\n\n $ flask --app flaskr init-db\n $ flask --app flaskr run --debug\n\nOpen http://127.0.0.1:5000 in a browser.\n\n\nTest\n----\n\n::\n\n $ pip install '.[test]'\n $ pytest\n\nRun with coverage report::\n\n $ coverage run -m pytest\n $ coverage report\n $ coverage html # open htmlcov/index.html in a browser\n"},{"col":4,"comment":"null","endLoc":250,"header":"def report_error(self, e)","id":951,"name":"report_error","nodeType":"Function","startLoc":244,"text":"def report_error(self, e):\n original = getattr(e, \"original_exception\", None)\n\n if original is not None:\n return f\"wrapped {type(original).__name__}\"\n\n return f\"direct {type(e).__name__}\""},{"id":952,"name":"next.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Keep Developing!\n================\n\nYou've learned about quite a few Flask and Python concepts throughout\nthe tutorial. Go back and review the tutorial and compare your code with\nthe steps you took to get there. Compare your project to the\n:gh:`example project `, which might look a bit\ndifferent due to the step-by-step nature of the tutorial.\n\nThere's a lot more to Flask than what you've seen so far. Even so,\nyou're now equipped to start developing your own web applications. Check\nout the :doc:`/quickstart` for an overview of what Flask can do, then\ndive into the docs to keep learning. Flask uses `Jinja`_, `Click`_,\n`Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have\ntheir own documentation too. You'll also be interested in\n:doc:`/extensions` which make tasks like working with the database or\nvalidating form data easier and more powerful.\n\nIf you want to keep developing your Flaskr project, here are some ideas\nfor what to try next:\n\n* A detail view to show a single post. Click a post's title to go to\n its page.\n* Like / unlike a post.\n* Comments.\n* Tags. Clicking a tag shows all the posts with that tag.\n* A search box that filters the index page by name.\n* Paged display. Only show 5 posts per page.\n* Upload an image to go along with a post.\n* Format posts using Markdown.\n* An RSS feed of new posts.\n\nHave fun and make awesome applications!\n\n.. _Jinja: https://palletsprojects.com/p/jinja/\n.. _Click: https://palletsprojects.com/p/click/\n.. _Werkzeug: https://palletsprojects.com/p/werkzeug/\n.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/\n"},{"id":953,"name":"MANIFEST.in","nodeType":"TextFile","path":"examples/tutorial","text":"include LICENSE.rst\ninclude flaskr/schema.sql\ngraft flaskr/static\ngraft flaskr/templates\ngraft tests\nglobal-exclude *.pyc\n"},{"col":0,"comment":"null","endLoc":112,"header":"def test_request_exception_signal()","id":954,"name":"test_request_exception_signal","nodeType":"Function","startLoc":95,"text":"def test_request_exception_signal():\n app = flask.Flask(__name__)\n recorded = []\n\n @app.route(\"/\")\n def index():\n 1 // 0\n\n def record(sender, exception):\n recorded.append(exception)\n\n flask.got_request_exception.connect(record, app)\n try:\n assert app.test_client().get(\"/\").status_code == 500\n assert len(recorded) == 1\n assert isinstance(recorded[0], ZeroDivisionError)\n finally:\n flask.got_request_exception.disconnect(record, app)"},{"col":0,"comment":"null","endLoc":22,"header":"@app.errorhandler(ValueError)\ndef handle_custom(e","id":955,"name":"handle_custom","nodeType":"Function","startLoc":20,"text":"@app.errorhandler(ValueError)\ndef handle_custom(e: ValueError) -> str:\n return \"\""},{"col":0,"comment":"null","endLoc":27,"header":"@app.errorhandler(ValueError)\ndef handle_accept_base(e","id":956,"name":"handle_accept_base","nodeType":"Function","startLoc":25,"text":"@app.errorhandler(ValueError)\ndef handle_accept_base(e: Exception) -> str:\n return \"\""},{"col":0,"comment":"null","endLoc":33,"header":"@app.errorhandler(BadRequest)\n@app.errorhandler(404)\ndef handle_multiple(e","id":957,"name":"handle_multiple","nodeType":"Function","startLoc":30,"text":"@app.errorhandler(BadRequest)\n@app.errorhandler(404)\ndef handle_multiple(e: BadRequest | NotFound) -> str:\n return \"\""},{"id":959,"name":"blueprints.rst","nodeType":"TextFile","path":"docs","text":"Modular Applications with Blueprints\n====================================\n\n.. currentmodule:: flask\n\n.. versionadded:: 0.7\n\nFlask uses a concept of *blueprints* for making application components and\nsupporting common patterns within an application or across applications.\nBlueprints can greatly simplify how large applications work and provide a\ncentral means for Flask extensions to register operations on applications.\nA :class:`Blueprint` object works similarly to a :class:`Flask`\napplication object, but it is not actually an application. Rather it is a\n*blueprint* of how to construct or extend an application.\n\nWhy Blueprints?\n---------------\n\nBlueprints in Flask are intended for these cases:\n\n* Factor an application into a set of blueprints. This is ideal for\n larger applications; a project could instantiate an application object,\n initialize several extensions, and register a collection of blueprints.\n* Register a blueprint on an application at a URL prefix and/or subdomain.\n Parameters in the URL prefix/subdomain become common view arguments\n (with defaults) across all view functions in the blueprint.\n* Register a blueprint multiple times on an application with different URL\n rules.\n* Provide template filters, static files, templates, and other utilities\n through blueprints. A blueprint does not have to implement applications\n or view functions.\n* Register a blueprint on an application for any of these cases when\n initializing a Flask extension.\n\nA blueprint in Flask is not a pluggable app because it is not actually an\napplication -- it's a set of operations which can be registered on an\napplication, even multiple times. Why not have multiple application\nobjects? You can do that (see :doc:`/patterns/appdispatch`), but your\napplications will have separate configs and will be managed at the WSGI\nlayer.\n\nBlueprints instead provide separation at the Flask level, share\napplication config, and can change an application object as necessary with\nbeing registered. The downside is that you cannot unregister a blueprint\nonce an application was created without having to destroy the whole\napplication object.\n\nThe Concept of Blueprints\n-------------------------\n\nThe basic concept of blueprints is that they record operations to execute\nwhen registered on an application. Flask associates view functions with\nblueprints when dispatching requests and generating URLs from one endpoint\nto another.\n\nMy First Blueprint\n------------------\n\nThis is what a very basic blueprint looks like. In this case we want to\nimplement a blueprint that does simple rendering of static templates::\n\n from flask import Blueprint, render_template, abort\n from jinja2 import TemplateNotFound\n\n simple_page = Blueprint('simple_page', __name__,\n template_folder='templates')\n\n @simple_page.route('/', defaults={'page': 'index'})\n @simple_page.route('/')\n def show(page):\n try:\n return render_template(f'pages/{page}.html')\n except TemplateNotFound:\n abort(404)\n\nWhen you bind a function with the help of the ``@simple_page.route``\ndecorator, the blueprint will record the intention of registering the\nfunction ``show`` on the application when it's later registered.\nAdditionally it will prefix the endpoint of the function with the\nname of the blueprint which was given to the :class:`Blueprint`\nconstructor (in this case also ``simple_page``). The blueprint's name\ndoes not modify the URL, only the endpoint.\n\nRegistering Blueprints\n----------------------\n\nSo how do you register that blueprint? Like this::\n\n from flask import Flask\n from yourapplication.simple_page import simple_page\n\n app = Flask(__name__)\n app.register_blueprint(simple_page)\n\nIf you check the rules registered on the application, you will find\nthese::\n\n >>> app.url_map\n Map([' (HEAD, OPTIONS, GET) -> static>,\n ' (HEAD, OPTIONS, GET) -> simple_page.show>,\n simple_page.show>])\n\nThe first one is obviously from the application itself for the static\nfiles. The other two are for the `show` function of the ``simple_page``\nblueprint. As you can see, they are also prefixed with the name of the\nblueprint and separated by a dot (``.``).\n\nBlueprints however can also be mounted at different locations::\n\n app.register_blueprint(simple_page, url_prefix='/pages')\n\nAnd sure enough, these are the generated rules::\n\n >>> app.url_map\n Map([' (HEAD, OPTIONS, GET) -> static>,\n ' (HEAD, OPTIONS, GET) -> simple_page.show>,\n simple_page.show>])\n\nOn top of that you can register blueprints multiple times though not every\nblueprint might respond properly to that. In fact it depends on how the\nblueprint is implemented if it can be mounted more than once.\n\nNesting Blueprints\n------------------\n\nIt is possible to register a blueprint on another blueprint.\n\n.. code-block:: python\n\n parent = Blueprint('parent', __name__, url_prefix='/parent')\n child = Blueprint('child', __name__, url_prefix='/child')\n parent.register_blueprint(child)\n app.register_blueprint(parent)\n\nThe child blueprint will gain the parent's name as a prefix to its\nname, and child URLs will be prefixed with the parent's URL prefix.\n\n.. code-block:: python\n\n url_for('parent.child.create')\n /parent/child/create\n\nIn addition a child blueprint's will gain their parent's subdomain,\nwith their subdomain as prefix if present i.e.\n\n.. code-block:: python\n\n parent = Blueprint('parent', __name__, subdomain='parent')\n child = Blueprint('child', __name__, subdomain='child')\n parent.register_blueprint(child)\n app.register_blueprint(parent)\n\n url_for('parent.child.create', _external=True)\n \"child.parent.domain.tld\"\n\nBlueprint-specific before request functions, etc. registered with the\nparent will trigger for the child. If a child does not have an error\nhandler that can handle a given exception, the parent's will be tried.\n\n\nBlueprint Resources\n-------------------\n\nBlueprints can provide resources as well. Sometimes you might want to\nintroduce a blueprint only for the resources it provides.\n\nBlueprint Resource Folder\n`````````````````````````\n\nLike for regular applications, blueprints are considered to be contained\nin a folder. While multiple blueprints can originate from the same folder,\nit does not have to be the case and it's usually not recommended.\n\nThe folder is inferred from the second argument to :class:`Blueprint` which\nis usually `__name__`. This argument specifies what logical Python\nmodule or package corresponds to the blueprint. If it points to an actual\nPython package that package (which is a folder on the filesystem) is the\nresource folder. If it's a module, the package the module is contained in\nwill be the resource folder. You can access the\n:attr:`Blueprint.root_path` property to see what the resource folder is::\n\n >>> simple_page.root_path\n '/Users/username/TestProject/yourapplication'\n\nTo quickly open sources from this folder you can use the\n:meth:`~Blueprint.open_resource` function::\n\n with simple_page.open_resource('static/style.css') as f:\n code = f.read()\n\nStatic Files\n````````````\n\nA blueprint can expose a folder with static files by providing the path\nto the folder on the filesystem with the ``static_folder`` argument.\nIt is either an absolute path or relative to the blueprint's location::\n\n admin = Blueprint('admin', __name__, static_folder='static')\n\nBy default the rightmost part of the path is where it is exposed on the\nweb. This can be changed with the ``static_url_path`` argument. Because the\nfolder is called ``static`` here it will be available at the\n``url_prefix`` of the blueprint + ``/static``. If the blueprint\nhas the prefix ``/admin``, the static URL will be ``/admin/static``.\n\nThe endpoint is named ``blueprint_name.static``. You can generate URLs\nto it with :func:`url_for` like you would with the static folder of the\napplication::\n\n url_for('admin.static', filename='style.css')\n\nHowever, if the blueprint does not have a ``url_prefix``, it is not\npossible to access the blueprint's static folder. This is because the\nURL would be ``/static`` in this case, and the application's ``/static``\nroute takes precedence. Unlike template folders, blueprint static\nfolders are not searched if the file does not exist in the application\nstatic folder.\n\nTemplates\n`````````\n\nIf you want the blueprint to expose templates you can do that by providing\nthe `template_folder` parameter to the :class:`Blueprint` constructor::\n\n admin = Blueprint('admin', __name__, template_folder='templates')\n\nFor static files, the path can be absolute or relative to the blueprint\nresource folder.\n\nThe template folder is added to the search path of templates but with a lower\npriority than the actual application's template folder. That way you can\neasily override templates that a blueprint provides in the actual application.\nThis also means that if you don't want a blueprint template to be accidentally\noverridden, make sure that no other blueprint or actual application template\nhas the same relative path. When multiple blueprints provide the same relative\ntemplate path the first blueprint registered takes precedence over the others.\n\n\nSo if you have a blueprint in the folder ``yourapplication/admin`` and you\nwant to render the template ``'admin/index.html'`` and you have provided\n``templates`` as a `template_folder` you will have to create a file like\nthis: :file:`yourapplication/admin/templates/admin/index.html`. The reason\nfor the extra ``admin`` folder is to avoid getting our template overridden\nby a template named ``index.html`` in the actual application template\nfolder.\n\nTo further reiterate this: if you have a blueprint named ``admin`` and you\nwant to render a template called :file:`index.html` which is specific to this\nblueprint, the best idea is to lay out your templates like this::\n\n yourpackage/\n blueprints/\n admin/\n templates/\n admin/\n index.html\n __init__.py\n\nAnd then when you want to render the template, use :file:`admin/index.html` as\nthe name to look up the template by. If you encounter problems loading\nthe correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config\nvariable which will instruct Flask to print out the steps it goes through\nto locate templates on every ``render_template`` call.\n\nBuilding URLs\n-------------\n\nIf you want to link from one page to another you can use the\n:func:`url_for` function just like you normally would do just that you\nprefix the URL endpoint with the name of the blueprint and a dot (``.``)::\n\n url_for('admin.index')\n\nAdditionally if you are in a view function of a blueprint or a rendered\ntemplate and you want to link to another endpoint of the same blueprint,\nyou can use relative redirects by prefixing the endpoint with a dot only::\n\n url_for('.index')\n\nThis will link to ``admin.index`` for instance in case the current request\nwas dispatched to any other admin blueprint endpoint.\n\n\nBlueprint Error Handlers\n------------------------\n\nBlueprints support the ``errorhandler`` decorator just like the :class:`Flask`\napplication object, so it is easy to make Blueprint-specific custom error\npages.\n\nHere is an example for a \"404 Page Not Found\" exception::\n\n @simple_page.errorhandler(404)\n def page_not_found(e):\n return render_template('pages/404.html')\n\nMost errorhandlers will simply work as expected; however, there is a caveat\nconcerning handlers for 404 and 405 exceptions. These errorhandlers are only\ninvoked from an appropriate ``raise`` statement or a call to ``abort`` in another\nof the blueprint's view functions; they are not invoked by, e.g., an invalid URL\naccess. This is because the blueprint does not \"own\" a certain URL space, so\nthe application instance has no way of knowing which blueprint error handler it\nshould run if given an invalid URL. If you would like to execute different\nhandling strategies for these errors based on URL prefixes, they may be defined\nat the application level using the ``request`` proxy object::\n\n @app.errorhandler(404)\n @app.errorhandler(405)\n def _handle_api_error(ex):\n if request.path.startswith('/api/'):\n return jsonify(error=str(ex)), ex.code\n else:\n return ex\n\nSee :doc:`/errorhandling`.\n"},{"id":960,"name":"examples/celery/src/task_app/templates","nodeType":"Package"},{"id":961,"name":"index.html","nodeType":"TextFile","path":"examples/celery/src/task_app/templates","text":"\n\n\n \n Celery Example\n\n\n

Celery Example

\nExecute background tasks with Celery. Submits tasks and shows results using JavaScript.\n\n
\n

Add

\n

Start a task to add two numbers, then poll for the result.\n

\n
\n
\n \n
\n

Result:

\n\n
\n

Block

\n

Start a task that takes 5 seconds. However, the response will return immediately.\n

\n \n
\n

\n\n
\n

Process

\n

Start a task that counts, waiting one second each time, showing progress.\n

\n
\n \n
\n

\n\n\n\n\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":10,"id":962,"name":"app","nodeType":"Attribute","startLoc":10,"text":"app"},{"col":0,"comment":"","endLoc":1,"header":"typing_error_handler.py#","id":963,"name":"","nodeType":"Function","startLoc":1,"text":"app = Flask(__name__)"},{"id":964,"name":"templates.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nTemplates\n=========\n\nYou've written the authentication views for your application, but if\nyou're running the server and try to go to any of the URLs, you'll see a\n``TemplateNotFound`` error. That's because the views are calling\n:func:`render_template`, but you haven't written the templates yet.\nThe template files will be stored in the ``templates`` directory inside\nthe ``flaskr`` package.\n\nTemplates are files that contain static data as well as placeholders\nfor dynamic data. A template is rendered with specific data to produce a\nfinal document. Flask uses the `Jinja`_ template library to render\ntemplates.\n\nIn your application, you will use templates to render `HTML`_ which\nwill display in the user's browser. In Flask, Jinja is configured to\n*autoescape* any data that is rendered in HTML templates. This means\nthat it's safe to render user input; any characters they've entered that\ncould mess with the HTML, such as ``<`` and ``>`` will be *escaped* with\n*safe* values that look the same in the browser but don't cause unwanted\neffects.\n\nJinja looks and behaves mostly like Python. Special delimiters are used\nto distinguish Jinja syntax from the static data in the template.\nAnything between ``{{`` and ``}}`` is an expression that will be output\nto the final document. ``{%`` and ``%}`` denotes a control flow\nstatement like ``if`` and ``for``. Unlike Python, blocks are denoted\nby start and end tags rather than indentation since static text within\na block could change indentation.\n\n.. _Jinja: https://jinja.palletsprojects.com/templates/\n.. _HTML: https://developer.mozilla.org/docs/Web/HTML\n\n\nThe Base Layout\n---------------\n\nEach page in the application will have the same basic layout around a\ndifferent body. Instead of writing the entire HTML structure in each\ntemplate, each template will *extend* a base template and override\nspecific sections.\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/base.html``\n\n \n {% block title %}{% endblock %} - Flaskr\n \n \n
\n
\n {% block header %}{% endblock %}\n
\n {% for message in get_flashed_messages() %}\n
{{ message }}
\n {% endfor %}\n {% block content %}{% endblock %}\n
\n\n:data:`g` is automatically available in templates. Based on if\n``g.user`` is set (from ``load_logged_in_user``), either the username\nand a log out link are displayed, or links to register and log in\nare displayed. :func:`url_for` is also automatically available, and is\nused to generate URLs to views instead of writing them out manually.\n\nAfter the page title, and before the content, the template loops over\neach message returned by :func:`get_flashed_messages`. You used\n:func:`flash` in the views to show error messages, and this is the code\nthat will display them.\n\nThere are three blocks defined here that will be overridden in the other\ntemplates:\n\n#. ``{% block title %}`` will change the title displayed in the\n browser's tab and window title.\n\n#. ``{% block header %}`` is similar to ``title`` but will change the\n title displayed on the page.\n\n#. ``{% block content %}`` is where the content of each page goes, such\n as the login form or a blog post.\n\nThe base template is directly in the ``templates`` directory. To keep\nthe others organized, the templates for a blueprint will be placed in a\ndirectory with the same name as the blueprint.\n\n\nRegister\n--------\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/auth/register.html``\n\n {% extends 'base.html' %}\n\n {% block header %}\n

{% block title %}Register{% endblock %}

\n {% endblock %}\n\n {% block content %}\n
\n \n \n \n \n \n
\n {% endblock %}\n\n``{% extends 'base.html' %}`` tells Jinja that this template should\nreplace the blocks from the base template. All the rendered content must\nappear inside ``{% block %}`` tags that override blocks from the base\ntemplate.\n\nA useful pattern used here is to place ``{% block title %}`` inside\n``{% block header %}``. This will set the title block and then output\nthe value of it into the header block, so that both the window and page\nshare the same title without writing it twice.\n\nThe ``input`` tags are using the ``required`` attribute here. This tells\nthe browser not to submit the form until those fields are filled in. If\nthe user is using an older browser that doesn't support that attribute,\nor if they are using something besides a browser to make requests, you\nstill want to validate the data in the Flask view. It's important to\nalways fully validate the data on the server, even if the client does\nsome validation as well.\n\n\nLog In\n------\n\nThis is identical to the register template except for the title and\nsubmit button.\n\n.. code-block:: html+jinja\n :caption: ``flaskr/templates/auth/login.html``\n\n {% extends 'base.html' %}\n\n {% block header %}\n

{% block title %}Log In{% endblock %}

\n {% endblock %}\n\n {% block content %}\n
\n \n \n \n \n \n
\n {% endblock %}\n\n\nRegister A User\n---------------\n\nNow that the authentication templates are written, you can register a\nuser. Make sure the server is still running (``flask run`` if it's not),\nthen go to http://127.0.0.1:5000/auth/register.\n\nTry clicking the \"Register\" button without filling out the form and see\nthat the browser shows an error message. Try removing the ``required``\nattributes from the ``register.html`` template and click \"Register\"\nagain. Instead of the browser showing an error, the page will reload and\nthe error from :func:`flash` in the view will be shown.\n\nFill out a username and password and you'll be redirected to the login\npage. Try entering an incorrect username, or the correct username and\nincorrect password. If you log in you'll get an error because there's\nno ``index`` view to redirect to yet.\n\nContinue to :doc:`static`.\n"},{"id":965,"name":".gitignore","nodeType":"TextFile","path":"examples/javascript","text":".venv/\n*.pyc\n__pycache__/\ninstance/\n.cache/\n.pytest_cache/\n.coverage\nhtmlcov/\ndist/\nbuild/\n*.egg-info/\n.idea/\n*.swp\n*~\n"},{"fileName":"app.py","filePath":"tests/test_apps/cliapp","id":966,"nodeType":"File","text":"from flask import Flask\n\ntestapp = Flask(\"testapp\")\n"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":967,"name":"testapp","nodeType":"Attribute","startLoc":3,"text":"testapp"},{"id":968,"name":"methodoverrides.rst","nodeType":"TextFile","path":"docs/patterns","text":"Adding HTTP Method Overrides\n============================\n\nSome HTTP proxies do not support arbitrary HTTP methods or newer HTTP\nmethods (such as PATCH). In that case it's possible to \"proxy\" HTTP\nmethods through another HTTP method in total violation of the protocol.\n\nThe way this works is by letting the client do an HTTP POST request and\nset the ``X-HTTP-Method-Override`` header. Then the method is replaced\nwith the header value before being passed to Flask.\n\nThis can be accomplished with an HTTP middleware::\n\n class HTTPMethodOverrideMiddleware(object):\n allowed_methods = frozenset([\n 'GET',\n 'HEAD',\n 'POST',\n 'DELETE',\n 'PUT',\n 'PATCH',\n 'OPTIONS'\n ])\n bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE'])\n\n def __init__(self, app):\n self.app = app\n\n def __call__(self, environ, start_response):\n method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()\n if method in self.allowed_methods:\n environ['REQUEST_METHOD'] = method\n if method in self.bodyless_methods:\n environ['CONTENT_LENGTH'] = '0'\n return self.app(environ, start_response)\n\nTo use this with Flask, wrap the app object with the middleware::\n\n from flask import Flask\n\n app = Flask(__name__)\n app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)\n"},{"fileName":"__init__.py","filePath":"examples/celery/src/task_app","id":969,"nodeType":"File","text":"from celery import Celery\nfrom celery import Task\nfrom flask import Flask\nfrom flask import render_template\n\n\ndef create_app() -> Flask:\n app = Flask(__name__)\n app.config.from_mapping(\n CELERY=dict(\n broker_url=\"redis://localhost\",\n result_backend=\"redis://localhost\",\n task_ignore_result=True,\n ),\n )\n app.config.from_prefixed_env()\n celery_init_app(app)\n\n @app.route(\"/\")\n def index() -> str:\n return render_template(\"index.html\")\n\n from . import views\n\n app.register_blueprint(views.bp)\n return app\n\n\ndef celery_init_app(app: Flask) -> Celery:\n class FlaskTask(Task):\n def __call__(self, *args: object, **kwargs: object) -> object:\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery_app = Celery(app.name, task_cls=FlaskTask)\n celery_app.config_from_object(app.config[\"CELERY\"])\n celery_app.set_default()\n app.extensions[\"celery\"] = celery_app\n return celery_app\n"},{"col":0,"comment":"null","endLoc":26,"header":"def create_app() -> Flask","id":970,"name":"create_app","nodeType":"Function","startLoc":7,"text":"def create_app() -> Flask:\n app = Flask(__name__)\n app.config.from_mapping(\n CELERY=dict(\n broker_url=\"redis://localhost\",\n result_backend=\"redis://localhost\",\n task_ignore_result=True,\n ),\n )\n app.config.from_prefixed_env()\n celery_init_app(app)\n\n @app.route(\"/\")\n def index() -> str:\n return render_template(\"index.html\")\n\n from . import views\n\n app.register_blueprint(views.bp)\n return app"},{"fileName":"test_views.py","filePath":"tests","id":972,"nodeType":"File","text":"import pytest\nfrom werkzeug.http import parse_set_header\n\nimport flask.views\n\n\ndef common_test(app):\n c = app.test_client()\n\n assert c.get(\"/\").data == b\"GET\"\n assert c.post(\"/\").data == b\"POST\"\n assert c.put(\"/\").status_code == 405\n meths = parse_set_header(c.open(\"/\", method=\"OPTIONS\").headers[\"Allow\"])\n assert sorted(meths) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]\n\n\ndef test_basic_view(app):\n class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n common_test(app)\n\n\ndef test_method_based_view(app):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n common_test(app)\n\n\ndef test_view_patching(app):\n class Index(flask.views.MethodView):\n def get(self):\n 1 // 0\n\n def post(self):\n 1 // 0\n\n class Other(Index):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n view = Index.as_view(\"index\")\n view.view_class = Other\n app.add_url_rule(\"/\", view_func=view)\n common_test(app)\n\n\ndef test_view_inheritance(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n class BetterIndex(Index):\n def delete(self):\n return \"DELETE\"\n\n app.add_url_rule(\"/\", view_func=BetterIndex.as_view(\"index\"))\n\n meths = parse_set_header(client.open(\"/\", method=\"OPTIONS\").headers[\"Allow\"])\n assert sorted(meths) == [\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]\n\n\ndef test_view_decorators(app, client):\n def add_x_parachute(f):\n def new_function(*args, **kwargs):\n resp = flask.make_response(f(*args, **kwargs))\n resp.headers[\"X-Parachute\"] = \"awesome\"\n return resp\n\n return new_function\n\n class Index(flask.views.View):\n decorators = [add_x_parachute]\n\n def dispatch_request(self):\n return \"Awesome\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.headers[\"X-Parachute\"] == \"awesome\"\n assert rv.data == b\"Awesome\"\n\n\ndef test_view_provide_automatic_options_attr():\n app = flask.Flask(__name__)\n\n class Index1(flask.views.View):\n provide_automatic_options = False\n\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index1.as_view(\"index\"))\n c = app.test_client()\n rv = c.open(\"/\", method=\"OPTIONS\")\n assert rv.status_code == 405\n\n app = flask.Flask(__name__)\n\n class Index2(flask.views.View):\n methods = [\"OPTIONS\"]\n provide_automatic_options = True\n\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index2.as_view(\"index\"))\n c = app.test_client()\n rv = c.open(\"/\", method=\"OPTIONS\")\n assert sorted(rv.allow) == [\"OPTIONS\"]\n\n app = flask.Flask(__name__)\n\n class Index3(flask.views.View):\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index3.as_view(\"index\"))\n c = app.test_client()\n rv = c.open(\"/\", method=\"OPTIONS\")\n assert \"OPTIONS\" in rv.allow\n\n\ndef test_implicit_head(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return flask.Response(\"Blub\", headers={\"X-Method\": flask.request.method})\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.data == b\"Blub\"\n assert rv.headers[\"X-Method\"] == \"GET\"\n rv = client.head(\"/\")\n assert rv.data == b\"\"\n assert rv.headers[\"X-Method\"] == \"HEAD\"\n\n\ndef test_explicit_head(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def head(self):\n return flask.Response(\"\", headers={\"X-Method\": \"HEAD\"})\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.data == b\"GET\"\n rv = client.head(\"/\")\n assert rv.data == b\"\"\n assert rv.headers[\"X-Method\"] == \"HEAD\"\n\n\ndef test_endpoint_override(app):\n app.debug = True\n\n class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n with pytest.raises(AssertionError):\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n # But these tests should still pass. We just log a warning.\n common_test(app)\n\n\ndef test_methods_var_inheritance(app, client):\n class BaseView(flask.views.MethodView):\n methods = [\"GET\", \"PROPFIND\"]\n\n class ChildView(BaseView):\n def get(self):\n return \"GET\"\n\n def propfind(self):\n return \"PROPFIND\"\n\n app.add_url_rule(\"/\", view_func=ChildView.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.open(\"/\", method=\"PROPFIND\").data == b\"PROPFIND\"\n assert ChildView.methods == {\"PROPFIND\", \"GET\"}\n\n\ndef test_multiple_inheritance(app, client):\n class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n class DeleteView(flask.views.MethodView):\n def delete(self):\n return \"DELETE\"\n\n class GetDeleteView(GetView, DeleteView):\n pass\n\n app.add_url_rule(\"/\", view_func=GetDeleteView.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.delete(\"/\").data == b\"DELETE\"\n assert sorted(GetDeleteView.methods) == [\"DELETE\", \"GET\"]\n\n\ndef test_remove_method_from_parent(app, client):\n class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n class OtherView(flask.views.MethodView):\n def post(self):\n return \"POST\"\n\n class View(GetView, OtherView):\n methods = [\"GET\"]\n\n app.add_url_rule(\"/\", view_func=View.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.post(\"/\").status_code == 405\n assert sorted(View.methods) == [\"GET\"]\n\n\ndef test_init_once(app, client):\n n = 0\n\n class CountInit(flask.views.View):\n init_every_request = False\n\n def __init__(self):\n nonlocal n\n n += 1\n\n def dispatch_request(self):\n return str(n)\n\n app.add_url_rule(\"/\", view_func=CountInit.as_view(\"index\"))\n assert client.get(\"/\").data == b\"1\"\n assert client.get(\"/\").data == b\"1\"\n"},{"col":0,"comment":"null","endLoc":14,"header":"def common_test(app)","id":974,"name":"common_test","nodeType":"Function","startLoc":7,"text":"def common_test(app):\n c = app.test_client()\n\n assert c.get(\"/\").data == b\"GET\"\n assert c.post(\"/\").data == b\"POST\"\n assert c.put(\"/\").status_code == 405\n meths = parse_set_header(c.open(\"/\", method=\"OPTIONS\").headers[\"Allow\"])\n assert sorted(meths) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]"},{"fileName":"__init__.py","filePath":"src/flask/json","id":975,"nodeType":"File","text":"from __future__ import annotations\n\nimport json as _json\nimport typing as t\n\nfrom ..globals import current_app\nfrom .provider import _default\n\nif t.TYPE_CHECKING: # pragma: no cover\n from ..wrappers import Response\n\n\ndef dumps(obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.dumps() `\n method, otherwise it will use :func:`json.dumps`.\n\n :param obj: The data to serialize.\n :param kwargs: Arguments passed to the ``dumps`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.dumps``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0.2\n :class:`decimal.Decimal` is supported by converting to a string.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n if current_app:\n return current_app.json.dumps(obj, **kwargs)\n\n kwargs.setdefault(\"default\", _default)\n return _json.dumps(obj, **kwargs)\n\n\ndef dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write to a file.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.dump() `\n method, otherwise it will use :func:`json.dump`.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: Arguments passed to the ``dump`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.dump``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0\n Writing to a binary file, and the ``encoding`` argument, will be\n removed in Flask 2.1.\n \"\"\"\n if current_app:\n current_app.json.dump(obj, fp, **kwargs)\n else:\n kwargs.setdefault(\"default\", _default)\n _json.dump(obj, fp, **kwargs)\n\n\ndef loads(s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.loads() `\n method, otherwise it will use :func:`json.loads`.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: Arguments passed to the ``loads`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.loads``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1. The data must be a\n string or UTF-8 bytes.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n if current_app:\n return current_app.json.loads(s, **kwargs)\n\n return _json.loads(s, **kwargs)\n\n\ndef load(fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON read from a file.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.load() `\n method, otherwise it will use :func:`json.load`.\n\n :param fp: A file opened for reading text or UTF-8 bytes.\n :param kwargs: Arguments passed to the ``load`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.load``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.2\n The ``app`` parameter will be removed in Flask 2.3.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1. The file must be text\n mode, or binary mode with UTF-8 bytes.\n \"\"\"\n if current_app:\n return current_app.json.load(fp, **kwargs)\n\n return _json.load(fp, **kwargs)\n\n\ndef jsonify(*args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with the ``application/json``\n mimetype. A dict or list returned from a view will be converted to a\n JSON response automatically without needing to call this.\n\n This requires an active request or application context, and calls\n :meth:`app.json.response() `.\n\n In debug mode, the output is formatted with indentation to make it\n easier to read. This may also be controlled by the provider.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.response``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0.2\n :class:`decimal.Decimal` is supported by converting to a string.\n\n .. versionchanged:: 0.11\n Added support for serializing top-level arrays. This was a\n security risk in ancient browsers. See :ref:`security-json`.\n\n .. versionadded:: 0.2\n \"\"\"\n return current_app.json.response(*args, **kwargs)\n"},{"col":0,"comment":"null","endLoc":120,"header":"def _default(o: t.Any) -> t.Any","id":977,"name":"_default","nodeType":"Function","startLoc":107,"text":"def _default(o: t.Any) -> t.Any:\n if isinstance(o, date):\n return http_date(o)\n\n if isinstance(o, (decimal.Decimal, uuid.UUID)):\n return str(o)\n\n if dataclasses and dataclasses.is_dataclass(o):\n return dataclasses.asdict(o)\n\n if hasattr(o, \"__html__\"):\n return str(o.__html__())\n\n raise TypeError(f\"Object of type {type(o).__name__} is not JSON serializable\")"},{"id":978,"name":"pull_request_template.md","nodeType":"TextFile","path":".github","text":"\n\n\n\n- fixes #\n\n\n\nChecklist:\n\n- [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change.\n- [ ] Add or update relevant docs, in the docs folder and in code.\n- [ ] Add an entry in `CHANGES.rst` summarizing the change and linking to the issue.\n- [ ] Add `.. versionchanged::` entries in any relevant code docs.\n- [ ] Run `pre-commit` hooks and fix any issues.\n- [ ] Run `pytest` and `tox`, no tests failed.\n"},{"col":4,"comment":"null","endLoc":99,"header":"def test_send_from_directory(self, app, req_ctx)","id":979,"name":"test_send_from_directory","nodeType":"Function","startLoc":92,"text":"def test_send_from_directory(self, app, req_ctx):\n app.root_path = os.path.join(\n os.path.dirname(__file__), \"test_apps\", \"subdomaintestmodule\"\n )\n rv = flask.send_from_directory(\"static\", \"hello.txt\")\n rv.direct_passthrough = False\n assert rv.data.strip() == b\"Hello Subdomain\"\n rv.close()"},{"fileName":"cli.py","filePath":"src/flask","id":980,"nodeType":"File","text":"from __future__ import annotations\n\nimport ast\nimport inspect\nimport os\nimport platform\nimport re\nimport sys\nimport traceback\nimport typing as t\nfrom functools import update_wrapper\nfrom operator import attrgetter\n\nimport click\nfrom click.core import ParameterSource\nfrom werkzeug import run_simple\nfrom werkzeug.serving import is_running_from_reloader\nfrom werkzeug.utils import import_string\n\nfrom .globals import current_app\nfrom .helpers import get_debug_flag\nfrom .helpers import get_load_dotenv\n\nif t.TYPE_CHECKING:\n from .app import Flask\n\n\nclass NoAppException(click.UsageError):\n \"\"\"Raised if an application cannot be found or loaded.\"\"\"\n\n\ndef find_best_app(module):\n \"\"\"Given a module instance this tries to find the best possible\n application in the module or raises an exception.\n \"\"\"\n from . import Flask\n\n # Search for the most common names first.\n for attr_name in (\"app\", \"application\"):\n app = getattr(module, attr_name, None)\n\n if isinstance(app, Flask):\n return app\n\n # Otherwise find the only object that is a Flask instance.\n matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]\n\n if len(matches) == 1:\n return matches[0]\n elif len(matches) > 1:\n raise NoAppException(\n \"Detected multiple Flask applications in module\"\n f\" '{module.__name__}'. Use '{module.__name__}:name'\"\n \" to specify the correct one.\"\n )\n\n # Search for app factory functions.\n for attr_name in (\"create_app\", \"make_app\"):\n app_factory = getattr(module, attr_name, None)\n\n if inspect.isfunction(app_factory):\n try:\n app = app_factory()\n\n if isinstance(app, Flask):\n return app\n except TypeError as e:\n if not _called_with_wrong_args(app_factory):\n raise\n\n raise NoAppException(\n f\"Detected factory '{attr_name}' in module '{module.__name__}',\"\n \" but could not call it without arguments. Use\"\n f\" '{module.__name__}:{attr_name}(args)'\"\n \" to specify arguments.\"\n ) from e\n\n raise NoAppException(\n \"Failed to find Flask application or factory in module\"\n f\" '{module.__name__}'. Use '{module.__name__}:name'\"\n \" to specify one.\"\n )\n\n\ndef _called_with_wrong_args(f):\n \"\"\"Check whether calling a function raised a ``TypeError`` because\n the call failed or because something in the factory raised the\n error.\n\n :param f: The function that was called.\n :return: ``True`` if the call failed.\n \"\"\"\n tb = sys.exc_info()[2]\n\n try:\n while tb is not None:\n if tb.tb_frame.f_code is f.__code__:\n # In the function, it was called successfully.\n return False\n\n tb = tb.tb_next\n\n # Didn't reach the function.\n return True\n finally:\n # Delete tb to break a circular reference.\n # https://docs.python.org/2/library/sys.html#sys.exc_info\n del tb\n\n\ndef find_app_by_string(module, app_name):\n \"\"\"Check if the given string is a variable name or a function. Call\n a function to get the app instance, or return the variable directly.\n \"\"\"\n from . import Flask\n\n # Parse app_name as a single expression to determine if it's a valid\n # attribute name or function call.\n try:\n expr = ast.parse(app_name.strip(), mode=\"eval\").body\n except SyntaxError:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n ) from None\n\n if isinstance(expr, ast.Name):\n name = expr.id\n args = []\n kwargs = {}\n elif isinstance(expr, ast.Call):\n # Ensure the function name is an attribute name only.\n if not isinstance(expr.func, ast.Name):\n raise NoAppException(\n f\"Function reference must be a simple name: {app_name!r}.\"\n )\n\n name = expr.func.id\n\n # Parse the positional and keyword arguments as literals.\n try:\n args = [ast.literal_eval(arg) for arg in expr.args]\n kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}\n except ValueError:\n # literal_eval gives cryptic error messages, show a generic\n # message with the full expression instead.\n raise NoAppException(\n f\"Failed to parse arguments as literal values: {app_name!r}.\"\n ) from None\n else:\n raise NoAppException(\n f\"Failed to parse {app_name!r} as an attribute name or function call.\"\n )\n\n try:\n attr = getattr(module, name)\n except AttributeError as e:\n raise NoAppException(\n f\"Failed to find attribute {name!r} in {module.__name__!r}.\"\n ) from e\n\n # If the attribute is a function, call it with any args and kwargs\n # to get the real application.\n if inspect.isfunction(attr):\n try:\n app = attr(*args, **kwargs)\n except TypeError as e:\n if not _called_with_wrong_args(attr):\n raise\n\n raise NoAppException(\n f\"The factory {app_name!r} in module\"\n f\" {module.__name__!r} could not be called with the\"\n \" specified arguments.\"\n ) from e\n else:\n app = attr\n\n if isinstance(app, Flask):\n return app\n\n raise NoAppException(\n \"A valid Flask application was not obtained from\"\n f\" '{module.__name__}:{app_name}'.\"\n )\n\n\ndef prepare_import(path):\n \"\"\"Given a filename this will try to calculate the python path, add it\n to the search path and return the actual module name that is expected.\n \"\"\"\n path = os.path.realpath(path)\n\n fname, ext = os.path.splitext(path)\n if ext == \".py\":\n path = fname\n\n if os.path.basename(path) == \"__init__\":\n path = os.path.dirname(path)\n\n module_name = []\n\n # move up until outside package structure (no __init__.py)\n while True:\n path, name = os.path.split(path)\n module_name.append(name)\n\n if not os.path.exists(os.path.join(path, \"__init__.py\")):\n break\n\n if sys.path[0] != path:\n sys.path.insert(0, path)\n\n return \".\".join(module_name[::-1])\n\n\ndef locate_app(module_name, app_name, raise_if_not_found=True):\n try:\n __import__(module_name)\n except ImportError:\n # Reraise the ImportError if it occurred within the imported module.\n # Determine this by checking whether the trace has a depth > 1.\n if sys.exc_info()[2].tb_next:\n raise NoAppException(\n f\"While importing {module_name!r}, an ImportError was\"\n f\" raised:\\n\\n{traceback.format_exc()}\"\n ) from None\n elif raise_if_not_found:\n raise NoAppException(f\"Could not import {module_name!r}.\") from None\n else:\n return\n\n module = sys.modules[module_name]\n\n if app_name is None:\n return find_best_app(module)\n else:\n return find_app_by_string(module, app_name)\n\n\ndef get_version(ctx, param, value):\n if not value or ctx.resilient_parsing:\n return\n\n import werkzeug\n from . import __version__\n\n click.echo(\n f\"Python {platform.python_version()}\\n\"\n f\"Flask {__version__}\\n\"\n f\"Werkzeug {werkzeug.__version__}\",\n color=ctx.color,\n )\n ctx.exit()\n\n\nversion_option = click.Option(\n [\"--version\"],\n help=\"Show the Flask version.\",\n expose_value=False,\n callback=get_version,\n is_flag=True,\n is_eager=True,\n)\n\n\nclass ScriptInfo:\n \"\"\"Helper object to deal with Flask applications. This is usually not\n necessary to interface with as it's used internally in the dispatching\n to click. In future versions of Flask this object will most likely play\n a bigger role. Typically it's created automatically by the\n :class:`FlaskGroup` but you can also manually create it and pass it\n onwards as click object.\n \"\"\"\n\n def __init__(\n self,\n app_import_path: str | None = None,\n create_app: t.Callable[..., Flask] | None = None,\n set_debug_flag: bool = True,\n ) -> None:\n #: Optionally the import path for the Flask application.\n self.app_import_path = app_import_path\n #: Optionally a function that is passed the script info to create\n #: the instance of the application.\n self.create_app = create_app\n #: A dictionary with arbitrary data that can be associated with\n #: this script info.\n self.data: t.Dict[t.Any, t.Any] = {}\n self.set_debug_flag = set_debug_flag\n self._loaded_app: Flask | None = None\n\n def load_app(self) -> Flask:\n \"\"\"Loads the Flask app (if not yet loaded) and returns it. Calling\n this multiple times will just result in the already loaded app to\n be returned.\n \"\"\"\n if self._loaded_app is not None:\n return self._loaded_app\n\n if self.create_app is not None:\n app = self.create_app()\n else:\n if self.app_import_path:\n path, name = (\n re.split(r\":(?![\\\\/])\", self.app_import_path, 1) + [None]\n )[:2]\n import_name = prepare_import(path)\n app = locate_app(import_name, name)\n else:\n for path in (\"wsgi.py\", \"app.py\"):\n import_name = prepare_import(path)\n app = locate_app(import_name, None, raise_if_not_found=False)\n\n if app:\n break\n\n if not app:\n raise NoAppException(\n \"Could not locate a Flask application. Use the\"\n \" 'flask --app' option, 'FLASK_APP' environment\"\n \" variable, or a 'wsgi.py' or 'app.py' file in the\"\n \" current directory.\"\n )\n\n if self.set_debug_flag:\n # Update the app's debug flag through the descriptor so that\n # other values repopulate as well.\n app.debug = get_debug_flag()\n\n self._loaded_app = app\n return app\n\n\npass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)\n\n\ndef with_appcontext(f):\n \"\"\"Wraps a callback so that it's guaranteed to be executed with the\n script's application context.\n\n Custom commands (and their options) registered under ``app.cli`` or\n ``blueprint.cli`` will always have an app context available, this\n decorator is not required in that case.\n\n .. versionchanged:: 2.2\n The app context is active for subcommands as well as the\n decorated callback. The app context is always available to\n ``app.cli`` command and parameter callbacks.\n \"\"\"\n\n @click.pass_context\n def decorator(__ctx, *args, **kwargs):\n if not current_app:\n app = __ctx.ensure_object(ScriptInfo).load_app()\n __ctx.with_resource(app.app_context())\n\n return __ctx.invoke(f, *args, **kwargs)\n\n return update_wrapper(decorator, f)\n\n\nclass AppGroup(click.Group):\n \"\"\"This works similar to a regular click :class:`~click.Group` but it\n changes the behavior of the :meth:`command` decorator so that it\n automatically wraps the functions in :func:`with_appcontext`.\n\n Not to be confused with :class:`FlaskGroup`.\n \"\"\"\n\n def command(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`\n unless it's disabled by passing ``with_appcontext=False``.\n \"\"\"\n wrap_for_ctx = kwargs.pop(\"with_appcontext\", True)\n\n def decorator(f):\n if wrap_for_ctx:\n f = with_appcontext(f)\n return click.Group.command(self, *args, **kwargs)(f)\n\n return decorator\n\n def group(self, *args, **kwargs):\n \"\"\"This works exactly like the method of the same name on a regular\n :class:`click.Group` but it defaults the group class to\n :class:`AppGroup`.\n \"\"\"\n kwargs.setdefault(\"cls\", AppGroup)\n return click.Group.group(self, *args, **kwargs)\n\n\ndef _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:\n if value is None:\n return None\n\n info = ctx.ensure_object(ScriptInfo)\n info.app_import_path = value\n return value\n\n\n# This option is eager so the app will be available if --help is given.\n# --help is also eager, so --app must be before it in the param list.\n# no_args_is_help bypasses eager processing, so this option must be\n# processed manually in that case to ensure FLASK_APP gets picked up.\n_app_option = click.Option(\n [\"-A\", \"--app\"],\n metavar=\"IMPORT\",\n help=(\n \"The Flask application or factory function to load, in the form 'module:name'.\"\n \" Module can be a dotted import or file path. Name is not required if it is\"\n \" 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to\"\n \" pass arguments.\"\n ),\n is_eager=True,\n expose_value=False,\n callback=_set_app,\n)\n\n\ndef _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:\n # If the flag isn't provided, it will default to False. Don't use\n # that, let debug be set by env in that case.\n source = ctx.get_parameter_source(param.name) # type: ignore[arg-type]\n\n if source is not None and source in (\n ParameterSource.DEFAULT,\n ParameterSource.DEFAULT_MAP,\n ):\n return None\n\n # Set with env var instead of ScriptInfo.load so that it can be\n # accessed early during a factory function.\n os.environ[\"FLASK_DEBUG\"] = \"1\" if value else \"0\"\n return value\n\n\n_debug_option = click.Option(\n [\"--debug/--no-debug\"],\n help=\"Set debug mode.\",\n expose_value=False,\n callback=_set_debug,\n)\n\n\ndef _env_file_callback(\n ctx: click.Context, param: click.Option, value: str | None\n) -> str | None:\n if value is None:\n return None\n\n import importlib\n\n try:\n importlib.import_module(\"dotenv\")\n except ImportError:\n raise click.BadParameter(\n \"python-dotenv must be installed to load an env file.\",\n ctx=ctx,\n param=param,\n ) from None\n\n # Don't check FLASK_SKIP_DOTENV, that only disables automatically\n # loading .env and .flaskenv files.\n load_dotenv(value)\n return value\n\n\n# This option is eager so env vars are loaded as early as possible to be\n# used by other options.\n_env_file_option = click.Option(\n [\"-e\", \"--env-file\"],\n type=click.Path(exists=True, dir_okay=False),\n help=\"Load environment variables from this file. python-dotenv must be installed.\",\n is_eager=True,\n expose_value=False,\n callback=_env_file_callback,\n)\n\n\nclass FlaskGroup(AppGroup):\n \"\"\"Special subclass of the :class:`AppGroup` group that supports\n loading more commands from the configured Flask app. Normally a\n developer does not have to interface with this class but there are\n some very advanced use cases for which it makes sense to create an\n instance of this. see :ref:`custom-scripts`.\n\n :param add_default_commands: if this is True then the default run and\n shell commands will be added.\n :param add_version_option: adds the ``--version`` option.\n :param create_app: an optional callback that is passed the script info and\n returns the loaded app.\n :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`\n files to set environment variables. Will also change the working\n directory to the directory containing the first file found.\n :param set_debug_flag: Set the app's debug flag.\n\n .. versionchanged:: 2.2\n Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.\n\n .. versionchanged:: 2.2\n An app context is pushed when running ``app.cli`` commands, so\n ``@with_appcontext`` is no longer required for those commands.\n\n .. versionchanged:: 1.0\n If installed, python-dotenv will be used to load environment variables\n from :file:`.env` and :file:`.flaskenv` files.\n \"\"\"\n\n def __init__(\n self,\n add_default_commands: bool = True,\n create_app: t.Callable[..., Flask] | None = None,\n add_version_option: bool = True,\n load_dotenv: bool = True,\n set_debug_flag: bool = True,\n **extra: t.Any,\n ) -> None:\n params = list(extra.pop(\"params\", None) or ())\n # Processing is done with option callbacks instead of a group\n # callback. This allows users to make a custom group callback\n # without losing the behavior. --env-file must come first so\n # that it is eagerly evaluated before --app.\n params.extend((_env_file_option, _app_option, _debug_option))\n\n if add_version_option:\n params.append(version_option)\n\n if \"context_settings\" not in extra:\n extra[\"context_settings\"] = {}\n\n extra[\"context_settings\"].setdefault(\"auto_envvar_prefix\", \"FLASK\")\n\n super().__init__(params=params, **extra)\n\n self.create_app = create_app\n self.load_dotenv = load_dotenv\n self.set_debug_flag = set_debug_flag\n\n if add_default_commands:\n self.add_command(run_command)\n self.add_command(shell_command)\n self.add_command(routes_command)\n\n self._loaded_plugin_commands = False\n\n def _load_plugin_commands(self):\n if self._loaded_plugin_commands:\n return\n\n if sys.version_info >= (3, 10):\n from importlib import metadata\n else:\n # Use a backport on Python < 3.10. We technically have\n # importlib.metadata on 3.8+, but the API changed in 3.10,\n # so use the backport for consistency.\n import importlib_metadata as metadata\n\n for ep in metadata.entry_points(group=\"flask.commands\"):\n self.add_command(ep.load(), ep.name)\n\n self._loaded_plugin_commands = True\n\n def get_command(self, ctx, name):\n self._load_plugin_commands()\n # Look up built-in and plugin commands, which should be\n # available even if the app fails to load.\n rv = super().get_command(ctx, name)\n\n if rv is not None:\n return rv\n\n info = ctx.ensure_object(ScriptInfo)\n\n # Look up commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n app = info.load_app()\n except NoAppException as e:\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n return None\n\n # Push an app context for the loaded app unless it is already\n # active somehow. This makes the context available to parameter\n # and command callbacks without needing @with_appcontext.\n if not current_app or current_app._get_current_object() is not app:\n ctx.with_resource(app.app_context())\n\n return app.cli.get_command(ctx, name)\n\n def list_commands(self, ctx):\n self._load_plugin_commands()\n # Start with the built-in and plugin commands.\n rv = set(super().list_commands(ctx))\n info = ctx.ensure_object(ScriptInfo)\n\n # Add commands provided by the app, showing an error and\n # continuing if the app couldn't be loaded.\n try:\n rv.update(info.load_app().cli.list_commands(ctx))\n except NoAppException as e:\n # When an app couldn't be loaded, show the error message\n # without the traceback.\n click.secho(f\"Error: {e.format_message()}\\n\", err=True, fg=\"red\")\n except Exception:\n # When any other errors occurred during loading, show the\n # full traceback.\n click.secho(f\"{traceback.format_exc()}\\n\", err=True, fg=\"red\")\n\n return sorted(rv)\n\n def make_context(\n self,\n info_name: str | None,\n args: list[str],\n parent: click.Context | None = None,\n **extra: t.Any,\n ) -> click.Context:\n # Set a flag to tell app.run to become a no-op. If app.run was\n # not in a __name__ == __main__ guard, it would start the server\n # when importing, blocking whatever command is being called.\n os.environ[\"FLASK_RUN_FROM_CLI\"] = \"true\"\n\n # Attempt to load .env and .flask env files. The --env-file\n # option can cause another file to be loaded.\n if get_load_dotenv(self.load_dotenv):\n load_dotenv()\n\n if \"obj\" not in extra and \"obj\" not in self.context_settings:\n extra[\"obj\"] = ScriptInfo(\n create_app=self.create_app, set_debug_flag=self.set_debug_flag\n )\n\n return super().make_context(info_name, args, parent=parent, **extra)\n\n def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:\n if not args and self.no_args_is_help:\n # Attempt to load --env-file and --app early in case they\n # were given as env vars. Otherwise no_args_is_help will not\n # see commands from app.cli.\n _env_file_option.handle_parse_result(ctx, {}, [])\n _app_option.handle_parse_result(ctx, {}, [])\n\n return super().parse_args(ctx, args)\n\n\ndef _path_is_ancestor(path, other):\n \"\"\"Take ``other`` and remove the length of ``path`` from it. Then join it\n to ``path``. If it is the original value, ``path`` is an ancestor of\n ``other``.\"\"\"\n return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other\n\n\ndef load_dotenv(path: str | os.PathLike | None = None) -> bool:\n \"\"\"Load \"dotenv\" files in order of precedence to set environment variables.\n\n If an env var is already set it is not overwritten, so earlier files in the\n list are preferred over later files.\n\n This is a no-op if `python-dotenv`_ is not installed.\n\n .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme\n\n :param path: Load the file at this location instead of searching.\n :return: ``True`` if a file was loaded.\n\n .. versionchanged:: 2.0\n The current directory is not changed to the location of the\n loaded file.\n\n .. versionchanged:: 2.0\n When loading the env files, set the default encoding to UTF-8.\n\n .. versionchanged:: 1.1.0\n Returns ``False`` when python-dotenv is not installed, or when\n the given path isn't a file.\n\n .. versionadded:: 1.0\n \"\"\"\n try:\n import dotenv\n except ImportError:\n if path or os.path.isfile(\".env\") or os.path.isfile(\".flaskenv\"):\n click.secho(\n \" * Tip: There are .env or .flaskenv files present.\"\n ' Do \"pip install python-dotenv\" to use them.',\n fg=\"yellow\",\n err=True,\n )\n\n return False\n\n # Always return after attempting to load a given path, don't load\n # the default files.\n if path is not None:\n if os.path.isfile(path):\n return dotenv.load_dotenv(path, encoding=\"utf-8\")\n\n return False\n\n loaded = False\n\n for name in (\".env\", \".flaskenv\"):\n path = dotenv.find_dotenv(name, usecwd=True)\n\n if not path:\n continue\n\n dotenv.load_dotenv(path, encoding=\"utf-8\")\n loaded = True\n\n return loaded # True if at least one file was located and loaded.\n\n\ndef show_server_banner(debug, app_import_path):\n \"\"\"Show extra startup messages the first time the server is run,\n ignoring the reloader.\n \"\"\"\n if is_running_from_reloader():\n return\n\n if app_import_path is not None:\n click.echo(f\" * Serving Flask app '{app_import_path}'\")\n\n if debug is not None:\n click.echo(f\" * Debug mode: {'on' if debug else 'off'}\")\n\n\nclass CertParamType(click.ParamType):\n \"\"\"Click option type for the ``--cert`` option. Allows either an\n existing file, the string ``'adhoc'``, or an import for a\n :class:`~ssl.SSLContext` object.\n \"\"\"\n\n name = \"path\"\n\n def __init__(self):\n self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)\n\n def convert(self, value, param, ctx):\n try:\n import ssl\n except ImportError:\n raise click.BadParameter(\n 'Using \"--cert\" requires Python to be compiled with SSL support.',\n ctx,\n param,\n ) from None\n\n try:\n return self.path_type(value, param, ctx)\n except click.BadParameter:\n value = click.STRING(value, param, ctx).lower()\n\n if value == \"adhoc\":\n try:\n import cryptography # noqa: F401\n except ImportError:\n raise click.BadParameter(\n \"Using ad-hoc certificates requires the cryptography library.\",\n ctx,\n param,\n ) from None\n\n return value\n\n obj = import_string(value, silent=True)\n\n if isinstance(obj, ssl.SSLContext):\n return obj\n\n raise\n\n\ndef _validate_key(ctx, param, value):\n \"\"\"The ``--key`` option must be specified when ``--cert`` is a file.\n Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.\n \"\"\"\n cert = ctx.params.get(\"cert\")\n is_adhoc = cert == \"adhoc\"\n\n try:\n import ssl\n except ImportError:\n is_context = False\n else:\n is_context = isinstance(cert, ssl.SSLContext)\n\n if value is not None:\n if is_adhoc:\n raise click.BadParameter(\n 'When \"--cert\" is \"adhoc\", \"--key\" is not used.', ctx, param\n )\n\n if is_context:\n raise click.BadParameter(\n 'When \"--cert\" is an SSLContext object, \"--key is not used.', ctx, param\n )\n\n if not cert:\n raise click.BadParameter('\"--cert\" must also be specified.', ctx, param)\n\n ctx.params[\"cert\"] = cert, value\n\n else:\n if cert and not (is_adhoc or is_context):\n raise click.BadParameter('Required when using \"--cert\".', ctx, param)\n\n return value\n\n\nclass SeparatedPathType(click.Path):\n \"\"\"Click option type that accepts a list of values separated by the\n OS's path separator (``:``, ``;`` on Windows). Each value is\n validated as a :class:`click.Path` type.\n \"\"\"\n\n def convert(self, value, param, ctx):\n items = self.split_envvar_value(value)\n super_convert = super().convert\n return [super_convert(item, param, ctx) for item in items]\n\n\n@click.command(\"run\", short_help=\"Run a development server.\")\n@click.option(\"--host\", \"-h\", default=\"127.0.0.1\", help=\"The interface to bind to.\")\n@click.option(\"--port\", \"-p\", default=5000, help=\"The port to bind to.\")\n@click.option(\n \"--cert\",\n type=CertParamType(),\n help=\"Specify a certificate file to use HTTPS.\",\n is_eager=True,\n)\n@click.option(\n \"--key\",\n type=click.Path(exists=True, dir_okay=False, resolve_path=True),\n callback=_validate_key,\n expose_value=False,\n help=\"The key file to use when specifying a certificate.\",\n)\n@click.option(\n \"--reload/--no-reload\",\n default=None,\n help=\"Enable or disable the reloader. By default the reloader \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--debugger/--no-debugger\",\n default=None,\n help=\"Enable or disable the debugger. By default the debugger \"\n \"is active if debug is enabled.\",\n)\n@click.option(\n \"--with-threads/--without-threads\",\n default=True,\n help=\"Enable or disable multithreading.\",\n)\n@click.option(\n \"--extra-files\",\n default=None,\n type=SeparatedPathType(),\n help=(\n \"Extra files that trigger a reload on change. Multiple paths\"\n f\" are separated by {os.path.pathsep!r}.\"\n ),\n)\n@click.option(\n \"--exclude-patterns\",\n default=None,\n type=SeparatedPathType(),\n help=(\n \"Files matching these fnmatch patterns will not trigger a reload\"\n \" on change. Multiple patterns are separated by\"\n f\" {os.path.pathsep!r}.\"\n ),\n)\n@pass_script_info\ndef run_command(\n info,\n host,\n port,\n reload,\n debugger,\n with_threads,\n cert,\n extra_files,\n exclude_patterns,\n):\n \"\"\"Run a local development server.\n\n This server is for development purposes only. It does not provide\n the stability, security, or performance of production WSGI servers.\n\n The reloader and debugger are enabled by default with the '--debug'\n option.\n \"\"\"\n try:\n app = info.load_app()\n except Exception as e:\n if is_running_from_reloader():\n # When reloading, print out the error immediately, but raise\n # it later so the debugger or server can handle it.\n traceback.print_exc()\n err = e\n\n def app(environ, start_response):\n raise err from None\n\n else:\n # When not reloading, raise the error immediately so the\n # command fails.\n raise e from None\n\n debug = get_debug_flag()\n\n if reload is None:\n reload = debug\n\n if debugger is None:\n debugger = debug\n\n show_server_banner(debug, info.app_import_path)\n\n run_simple(\n host,\n port,\n app,\n use_reloader=reload,\n use_debugger=debugger,\n threaded=with_threads,\n ssl_context=cert,\n extra_files=extra_files,\n exclude_patterns=exclude_patterns,\n )\n\n\nrun_command.params.insert(0, _debug_option)\n\n\n@click.command(\"shell\", short_help=\"Run a shell in the app context.\")\n@with_appcontext\ndef shell_command() -> None:\n \"\"\"Run an interactive Python shell in the context of a given\n Flask application. The application will populate the default\n namespace of this shell according to its configuration.\n\n This is useful for executing small snippets of management code\n without having to manually configure the application.\n \"\"\"\n import code\n\n banner = (\n f\"Python {sys.version} on {sys.platform}\\n\"\n f\"App: {current_app.import_name}\\n\"\n f\"Instance: {current_app.instance_path}\"\n )\n ctx: dict = {}\n\n # Support the regular Python interpreter startup script if someone\n # is using it.\n startup = os.environ.get(\"PYTHONSTARTUP\")\n if startup and os.path.isfile(startup):\n with open(startup) as f:\n eval(compile(f.read(), startup, \"exec\"), ctx)\n\n ctx.update(current_app.make_shell_context())\n\n # Site, customize, or startup script can set a hook to call when\n # entering interactive mode. The default one sets up readline with\n # tab and history completion.\n interactive_hook = getattr(sys, \"__interactivehook__\", None)\n\n if interactive_hook is not None:\n try:\n import readline\n from rlcompleter import Completer\n except ImportError:\n pass\n else:\n # rlcompleter uses __main__.__dict__ by default, which is\n # flask.__main__. Use the shell context instead.\n readline.set_completer(Completer(ctx).complete)\n\n interactive_hook()\n\n code.interact(banner=banner, local=ctx)\n\n\n@click.command(\"routes\", short_help=\"Show the routes for the app.\")\n@click.option(\n \"--sort\",\n \"-s\",\n type=click.Choice((\"endpoint\", \"methods\", \"rule\", \"match\")),\n default=\"endpoint\",\n help=(\n 'Method to sort routes by. \"match\" is the order that Flask will match '\n \"routes when dispatching a request.\"\n ),\n)\n@click.option(\"--all-methods\", is_flag=True, help=\"Show HEAD and OPTIONS methods.\")\n@with_appcontext\ndef routes_command(sort: str, all_methods: bool) -> None:\n \"\"\"Show all registered routes with endpoints and methods.\"\"\"\n\n rules = list(current_app.url_map.iter_rules())\n if not rules:\n click.echo(\"No routes were registered.\")\n return\n\n ignored_methods = set(() if all_methods else (\"HEAD\", \"OPTIONS\"))\n\n if sort in (\"endpoint\", \"rule\"):\n rules = sorted(rules, key=attrgetter(sort))\n elif sort == \"methods\":\n rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore\n\n rule_methods = [\n \", \".join(sorted(rule.methods - ignored_methods)) # type: ignore\n for rule in rules\n ]\n\n headers = (\"Endpoint\", \"Methods\", \"Rule\")\n widths = (\n max(len(rule.endpoint) for rule in rules),\n max(len(methods) for methods in rule_methods),\n max(len(rule.rule) for rule in rules),\n )\n widths = [max(len(h), w) for h, w in zip(headers, widths)]\n row = \"{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}\".format(*widths)\n\n click.echo(row.format(*headers).strip())\n click.echo(row.format(*(\"-\" * width for width in widths)))\n\n for rule, methods in zip(rules, rule_methods):\n click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())\n\n\ncli = FlaskGroup(\n name=\"flask\",\n help=\"\"\"\\\nA general utility script for Flask applications.\n\nAn application to load must be given with the '--app' option,\n'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file\nin the current directory.\n\"\"\",\n)\n\n\ndef main() -> None:\n cli.main()\n\n\nif __name__ == \"__main__\":\n main()\n"},{"className":"TaggedJSONSerializer","col":0,"comment":"Serializer that uses a tag system to compactly represent objects that\n are not JSON types. Passed as the intermediate serializer to\n :class:`itsdangerous.Serializer`.\n\n The following extra types are supported:\n\n * :class:`dict`\n * :class:`tuple`\n * :class:`bytes`\n * :class:`~markupsafe.Markup`\n * :class:`~uuid.UUID`\n * :class:`~datetime.datetime`\n ","endLoc":312,"id":981,"nodeType":"Class","startLoc":216,"text":"class TaggedJSONSerializer:\n \"\"\"Serializer that uses a tag system to compactly represent objects that\n are not JSON types. Passed as the intermediate serializer to\n :class:`itsdangerous.Serializer`.\n\n The following extra types are supported:\n\n * :class:`dict`\n * :class:`tuple`\n * :class:`bytes`\n * :class:`~markupsafe.Markup`\n * :class:`~uuid.UUID`\n * :class:`~datetime.datetime`\n \"\"\"\n\n __slots__ = (\"tags\", \"order\")\n\n #: Tag classes to bind when creating the serializer. Other tags can be\n #: added later using :meth:`~register`.\n default_tags = [\n TagDict,\n PassDict,\n TagTuple,\n PassList,\n TagBytes,\n TagMarkup,\n TagUUID,\n TagDateTime,\n ]\n\n def __init__(self) -> None:\n self.tags: t.Dict[str, JSONTag] = {}\n self.order: t.List[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)\n\n def register(\n self,\n tag_class: t.Type[JSONTag],\n force: bool = False,\n index: t.Optional[int] = None,\n ) -> None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n \"\"\"\n tag = tag_class(self)\n key = tag.key\n\n if key is not None:\n if not force and key in self.tags:\n raise KeyError(f\"Tag '{key}' is already registered.\")\n\n self.tags[key] = tag\n\n if index is None:\n self.order.append(tag)\n else:\n self.order.insert(index, tag)\n\n def tag(self, value: t.Any) -> t.Dict[str, t.Any]:\n \"\"\"Convert a value to a tagged representation if necessary.\"\"\"\n for tag in self.order:\n if tag.check(value):\n return tag.tag(value)\n\n return value\n\n def untag(self, value: t.Dict[str, t.Any]) -> t.Any:\n \"\"\"Convert a tagged representation back to the original type.\"\"\"\n if len(value) != 1:\n return value\n\n key = next(iter(value))\n\n if key not in self.tags:\n return value\n\n return self.tags[key].to_python(value[key])\n\n def dumps(self, value: t.Any) -> str:\n \"\"\"Tag the value and dump it to a compact JSON string.\"\"\"\n return dumps(self.tag(value), separators=(\",\", \":\"))\n\n def loads(self, value: str) -> t.Any:\n \"\"\"Load data from a JSON string and deserialized any tagged objects.\"\"\"\n return loads(value, object_hook=self.untag)"},{"col":0,"comment":"null","endLoc":1778,"header":"@overload\ndef sorted(\n __iterable: Iterable[SupportsRichComparisonT], *, key: None = None, reverse: bool = False\n) -> list[SupportsRichComparisonT]","id":982,"name":"sorted","nodeType":"Function","startLoc":1775,"text":"@overload\ndef sorted(\n __iterable: Iterable[SupportsRichComparisonT], *, key: None = None, reverse: bool = False\n) -> list[SupportsRichComparisonT]: ..."},{"className":"StatusJSON","col":0,"comment":"null","endLoc":44,"id":983,"nodeType":"Class","startLoc":43,"text":"class StatusJSON(te.TypedDict):\n status: str"},{"col":0,"comment":"null","endLoc":1780,"header":"@overload\ndef sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> list[_T]","id":984,"name":"sorted","nodeType":"Function","startLoc":1779,"text":"@overload\ndef sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> list[_T]: ..."},{"col":0,"comment":"null","endLoc":25,"header":"def test_basic_view(app)","id":985,"name":"test_basic_view","nodeType":"Function","startLoc":17,"text":"def test_basic_view(app):\n class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n common_test(app)"},{"col":0,"comment":"null","endLoc":136,"header":"def test_appcontext_signals(app, client)","id":986,"name":"test_appcontext_signals","nodeType":"Function","startLoc":115,"text":"def test_appcontext_signals(app, client):\n recorded = []\n\n def record_push(sender, **kwargs):\n recorded.append(\"push\")\n\n def record_pop(sender, **kwargs):\n recorded.append(\"pop\")\n\n @app.route(\"/\")\n def index():\n return \"Hello\"\n\n flask.appcontext_pushed.connect(record_push, app)\n flask.appcontext_popped.connect(record_pop, app)\n try:\n rv = client.get(\"/\")\n assert rv.data == b\"Hello\"\n assert recorded == [\"push\", \"pop\"]\n finally:\n flask.appcontext_pushed.disconnect(record_push, app)\n flask.appcontext_popped.disconnect(record_pop, app)"},{"attributeType":"str","col":4,"comment":"null","endLoc":44,"id":987,"name":"status","nodeType":"Attribute","startLoc":44,"text":"status"},{"col":0,"comment":"","endLoc":1,"header":"app.py#","id":989,"name":"","nodeType":"Function","startLoc":1,"text":"testapp = Flask(\"testapp\")"},{"col":0,"comment":"null","endLoc":38,"header":"def test_method_based_view(app)","id":990,"name":"test_method_based_view","nodeType":"Function","startLoc":28,"text":"def test_method_based_view(app):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n common_test(app)"},{"id":991,"name":"template_filter.html","nodeType":"TextFile","path":"tests/templates","text":"{{ value|super_reverse }}\n"},{"className":"attrgetter","col":0,"comment":"null","endLoc":104,"id":992,"nodeType":"Class","startLoc":92,"text":"@final\nclass attrgetter(Generic[_T_co]):\n @overload\n def __new__(cls, attr: str) -> attrgetter[Any]: ...\n @overload\n def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ...\n @overload\n def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ...\n @overload\n def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ...\n @overload\n def __new__(cls, attr: str, *attrs: str) -> attrgetter[tuple[Any, ...]]: ...\n def __call__(self, obj: Any) -> _T_co: ..."},{"col":0,"comment":"null","endLoc":59,"header":"def test_view_patching(app)","id":993,"name":"test_view_patching","nodeType":"Function","startLoc":41,"text":"def test_view_patching(app):\n class Index(flask.views.MethodView):\n def get(self):\n 1 // 0\n\n def post(self):\n 1 // 0\n\n class Other(Index):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n view = Index.as_view(\"index\")\n view.view_class = Other\n app.add_url_rule(\"/\", view_func=view)\n common_test(app)"},{"col":0,"comment":"null","endLoc":160,"header":"def test_flash_signal(app)","id":995,"name":"test_flash_signal","nodeType":"Function","startLoc":139,"text":"def test_flash_signal(app):\n @app.route(\"/\")\n def index():\n flask.flash(\"This is a flash message\", category=\"notice\")\n return flask.redirect(\"/other\")\n\n recorded = []\n\n def record(sender, message, category):\n recorded.append((message, category))\n\n flask.message_flashed.connect(record, app)\n try:\n client = app.test_client()\n with client.session_transaction():\n client.get(\"/\")\n assert len(recorded) == 1\n message, category = recorded[0]\n assert message == \"This is a flash message\"\n assert category == \"notice\"\n finally:\n flask.message_flashed.disconnect(record, app)"},{"className":"TestUrlFor","col":0,"comment":"null","endLoc":162,"id":996,"nodeType":"Class","startLoc":102,"text":"class TestUrlFor:\n def test_url_for_with_anchor(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _anchor=\"x y\") == \"/#x%20y\"\n\n def test_url_for_with_scheme(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )\n\n def test_url_for_with_scheme_not_external(self, app, req_ctx):\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n # Implicit external with scheme.\n url = flask.url_for(\"index\", _scheme=\"https\")\n assert url == \"https://localhost/\"\n\n # Error when external=False with scheme\n with pytest.raises(ValueError):\n flask.url_for(\"index\", _scheme=\"https\", _external=False)\n\n def test_url_for_with_alternating_schemes(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\"\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\"\n\n def test_url_with_method(self, app, req_ctx):\n from flask.views import MethodView\n\n class MyView(MethodView):\n def get(self, id=None):\n if id is None:\n return \"List\"\n return f\"Get {id:d}\"\n\n def post(self):\n return \"Create\"\n\n myview = MyView.as_view(\"myview\")\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/create\", methods=[\"POST\"], view_func=myview)\n\n assert flask.url_for(\"myview\", _method=\"GET\") == \"/myview/\"\n assert flask.url_for(\"myview\", id=42, _method=\"GET\") == \"/myview/42\"\n assert flask.url_for(\"myview\", _method=\"POST\") == \"/myview/create\""},{"col":0,"comment":"null","endLoc":28,"header":"def test_uninstalled_module_paths(modules_tmpdir, purge_module)","id":997,"name":"test_uninstalled_module_paths","nodeType":"Function","startLoc":17,"text":"def test_uninstalled_module_paths(modules_tmpdir, purge_module):\n app = modules_tmpdir.join(\"config_module_app.py\").write(\n \"import os\\n\"\n \"import flask\\n\"\n \"here = os.path.abspath(os.path.dirname(__file__))\\n\"\n \"app = flask.Flask(__name__)\\n\"\n )\n purge_module(\"config_module_app\")\n\n from config_module_app import app\n\n assert app.instance_path == str(modules_tmpdir.join(\"instance\"))"},{"col":4,"comment":"null","endLoc":108,"header":"def test_url_for_with_anchor(self, app, req_ctx)","id":998,"name":"test_url_for_with_anchor","nodeType":"Function","startLoc":103,"text":"def test_url_for_with_anchor(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _anchor=\"x y\") == \"/#x%20y\""},{"col":4,"comment":"null","endLoc":118,"header":"def test_url_for_with_scheme(self, app, req_ctx)","id":999,"name":"test_url_for_with_scheme","nodeType":"Function","startLoc":110,"text":"def test_url_for_with_scheme(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )"},{"col":4,"comment":"null","endLoc":251,"header":"def __init__(self) -> None","id":1000,"name":"__init__","nodeType":"Function","startLoc":246,"text":"def __init__(self) -> None:\n self.tags: t.Dict[str, JSONTag] = {}\n self.order: t.List[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)"},{"col":0,"comment":"null","endLoc":77,"header":"def test_view_inheritance(app, client)","id":1001,"name":"test_view_inheritance","nodeType":"Function","startLoc":62,"text":"def test_view_inheritance(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def post(self):\n return \"POST\"\n\n class BetterIndex(Index):\n def delete(self):\n return \"DELETE\"\n\n app.add_url_rule(\"/\", view_func=BetterIndex.as_view(\"index\"))\n\n meths = parse_set_header(client.open(\"/\", method=\"OPTIONS\").headers[\"Allow\"])\n assert sorted(meths) == [\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]"},{"col":4,"comment":"null","endLoc":129,"header":"def test_url_for_with_scheme_not_external(self, app, req_ctx)","id":1002,"name":"test_url_for_with_scheme_not_external","nodeType":"Function","startLoc":120,"text":"def test_url_for_with_scheme_not_external(self, app, req_ctx):\n app.add_url_rule(\"/\", endpoint=\"index\")\n\n # Implicit external with scheme.\n url = flask.url_for(\"index\", _scheme=\"https\")\n assert url == \"https://localhost/\"\n\n # Error when external=False with scheme\n with pytest.raises(ValueError):\n flask.url_for(\"index\", _scheme=\"https\", _external=False)"},{"id":1003,"name":"deploy.rst","nodeType":"TextFile","path":"docs/tutorial","text":"Deploy to Production\n====================\n\nThis part of the tutorial assumes you have a server that you want to\ndeploy your application to. It gives an overview of how to create the\ndistribution file and install it, but won't go into specifics about\nwhat server or software to use. You can set up a new environment on your\ndevelopment computer to try out the instructions below, but probably\nshouldn't use it for hosting a real public application. See\n:doc:`/deploying/index` for a list of many different ways to host your\napplication.\n\n\nBuild and Install\n-----------------\n\nWhen you want to deploy your application elsewhere, you build a *wheel*\n(``.whl``) file. Install and use the ``build`` tool to do this.\n\n.. code-block:: none\n\n $ pip install build\n $ python -m build --wheel\n\nYou can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The\nfile name is in the format of {project name}-{version}-{python tag}\n-{abi tag}-{platform tag}.\n\nCopy this file to another machine,\n:ref:`set up a new virtualenv `, then install the\nfile with ``pip``.\n\n.. code-block:: none\n\n $ pip install flaskr-1.0.0-py3-none-any.whl\n\nPip will install your project along with its dependencies.\n\nSince this is a different machine, you need to run ``init-db`` again to\ncreate the database in the instance folder.\n\n .. code-block:: text\n\n $ flask --app flaskr init-db\n\nWhen Flask detects that it's installed (not in editable mode), it uses\na different directory for the instance folder. You can find it at\n``.venv/var/flaskr-instance`` instead.\n\n\nConfigure the Secret Key\n------------------------\n\nIn the beginning of the tutorial that you gave a default value for\n:data:`SECRET_KEY`. This should be changed to some random bytes in\nproduction. Otherwise, attackers could use the public ``'dev'`` key to\nmodify the session cookie, or anything else that uses the secret key.\n\nYou can use the following command to output a random secret key:\n\n.. code-block:: none\n\n $ python -c 'import secrets; print(secrets.token_hex())'\n\n '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'\n\nCreate the ``config.py`` file in the instance folder, which the factory\nwill read from if it exists. Copy the generated value into it.\n\n.. code-block:: python\n :caption: ``.venv/var/flaskr-instance/config.py``\n\n SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'\n\nYou can also set any other necessary configuration here, although\n``SECRET_KEY`` is the only one needed for Flaskr.\n\n\nRun with a Production Server\n----------------------------\n\nWhen running publicly rather than in development, you should not use the\nbuilt-in development server (``flask run``). The development server is\nprovided by Werkzeug for convenience, but is not designed to be\nparticularly efficient, stable, or secure.\n\nInstead, use a production WSGI server. For example, to use `Waitress`_,\nfirst install it in the virtual environment:\n\n.. code-block:: none\n\n $ pip install waitress\n\nYou need to tell Waitress about your application, but it doesn't use\n``--app`` like ``flask run`` does. You need to tell it to import and\ncall the application factory to get an application object.\n\n.. code-block:: none\n\n $ waitress-serve --call 'flaskr:create_app'\n\n Serving on http://0.0.0.0:8080\n\nSee :doc:`/deploying/index` for a list of many different ways to host\nyour application. Waitress is just an example, chosen for the tutorial\nbecause it supports both Windows and Linux. There are many more WSGI\nservers and deployment options that you may choose for your project.\n\n.. _Waitress: https://docs.pylonsproject.org/projects/waitress/en/stable/\n\nContinue to :doc:`next`.\n"},{"col":0,"comment":"null","endLoc":98,"header":"def test_view_decorators(app, client)","id":1004,"name":"test_view_decorators","nodeType":"Function","startLoc":80,"text":"def test_view_decorators(app, client):\n def add_x_parachute(f):\n def new_function(*args, **kwargs):\n resp = flask.make_response(f(*args, **kwargs))\n resp.headers[\"X-Parachute\"] = \"awesome\"\n return resp\n\n return new_function\n\n class Index(flask.views.View):\n decorators = [add_x_parachute]\n\n def dispatch_request(self):\n return \"Awesome\"\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.headers[\"X-Parachute\"] == \"awesome\"\n assert rv.data == b\"Awesome\""},{"col":4,"comment":"null","endLoc":141,"header":"def test_url_for_with_alternating_schemes(self, app, req_ctx)","id":1005,"name":"test_url_for_with_alternating_schemes","nodeType":"Function","startLoc":131,"text":"def test_url_for_with_alternating_schemes(self, app, req_ctx):\n @app.route(\"/\")\n def index():\n return \"42\"\n\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\"\n assert (\n flask.url_for(\"index\", _external=True, _scheme=\"https\")\n == \"https://localhost/\"\n )\n assert flask.url_for(\"index\", _external=True) == \"http://localhost/\""},{"col":0,"comment":"null","endLoc":138,"header":"def test_view_provide_automatic_options_attr()","id":1006,"name":"test_view_provide_automatic_options_attr","nodeType":"Function","startLoc":101,"text":"def test_view_provide_automatic_options_attr():\n app = flask.Flask(__name__)\n\n class Index1(flask.views.View):\n provide_automatic_options = False\n\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index1.as_view(\"index\"))\n c = app.test_client()\n rv = c.open(\"/\", method=\"OPTIONS\")\n assert rv.status_code == 405\n\n app = flask.Flask(__name__)\n\n class Index2(flask.views.View):\n methods = [\"OPTIONS\"]\n provide_automatic_options = True\n\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index2.as_view(\"index\"))\n c = app.test_client()\n rv = c.open(\"/\", method=\"OPTIONS\")\n assert sorted(rv.allow) == [\"OPTIONS\"]\n\n app = flask.Flask(__name__)\n\n class Index3(flask.views.View):\n def dispatch_request(self):\n return \"Hello World!\"\n\n app.add_url_rule(\"/\", view_func=Index3.as_view(\"index\"))\n c = app.test_client()\n rv = c.open(\"/\", method=\"OPTIONS\")\n assert \"OPTIONS\" in rv.allow"},{"col":4,"comment":"null","endLoc":202,"header":"def test_greenlet_context_copying_api(self, app, client)","id":1007,"name":"test_greenlet_context_copying_api","nodeType":"Function","startLoc":179,"text":"def test_greenlet_context_copying_api(self, app, client):\n greenlets = []\n\n @app.route(\"/\")\n def index():\n flask.session[\"fizz\"] = \"buzz\"\n\n @flask.copy_current_request_context\n def g():\n assert flask.request\n assert flask.current_app == app\n assert flask.request.path == \"/\"\n assert flask.request.args[\"foo\"] == \"bar\"\n assert flask.session.get(\"fizz\") == \"buzz\"\n return 42\n\n greenlets.append(greenlet(g))\n return \"Hello World!\"\n\n rv = client.get(\"/?foo=bar\")\n assert rv.data == b\"Hello World!\"\n\n result = greenlets[0].run()\n assert result == 42"},{"id":1008,"name":"config.rst","nodeType":"TextFile","path":"docs","text":"Configuration Handling\n======================\n\nApplications need some kind of configuration. There are different settings\nyou might want to change depending on the application environment like\ntoggling the debug mode, setting the secret key, and other such\nenvironment-specific things.\n\nThe way Flask is designed usually requires the configuration to be\navailable when the application starts up. You can hard code the\nconfiguration in the code, which for many small applications is not\nactually that bad, but there are better ways.\n\nIndependent of how you load your config, there is a config object\navailable which holds the loaded configuration values:\nThe :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`\nobject. This is the place where Flask itself puts certain configuration\nvalues and also where extensions can put their configuration values. But\nthis is also where you can have your own configuration.\n\n\nConfiguration Basics\n--------------------\n\nThe :attr:`~flask.Flask.config` is actually a subclass of a dictionary and\ncan be modified just like any dictionary::\n\n app = Flask(__name__)\n app.config['TESTING'] = True\n\nCertain configuration values are also forwarded to the\n:attr:`~flask.Flask` object so you can read and write them from there::\n\n app.testing = True\n\nTo update multiple keys at once you can use the :meth:`dict.update`\nmethod::\n\n app.config.update(\n TESTING=True,\n SECRET_KEY='192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'\n )\n\n\nDebug Mode\n----------\n\nThe :data:`DEBUG` config value is special because it may behave inconsistently if\nchanged after the app has begun setting up. In order to set debug mode reliably, use the\n``--debug`` option on the ``flask`` or ``flask run`` command. ``flask run`` will use the\ninteractive debugger and reloader by default in debug mode.\n\n.. code-block:: text\n\n $ flask --app hello run --debug\n\nUsing the option is recommended. While it is possible to set :data:`DEBUG` in your\nconfig or code, this is strongly discouraged. It can't be read early by the\n``flask run`` command, and some systems or extensions may have already configured\nthemselves based on a previous value.\n\n\nBuiltin Configuration Values\n----------------------------\n\nThe following configuration values are used internally by Flask:\n\n.. py:data:: DEBUG\n\n Whether debug mode is enabled. When using ``flask run`` to start the development\n server, an interactive debugger will be shown for unhandled exceptions, and the\n server will be reloaded when code changes. The :attr:`~flask.Flask.debug` attribute\n maps to this config key. This is set with the ``FLASK_DEBUG`` environment variable.\n It may not behave as expected if set in code.\n\n **Do not enable debug mode when deploying in production.**\n\n Default: ``False``\n\n.. py:data:: TESTING\n\n Enable testing mode. Exceptions are propagated rather than handled by the\n the app's error handlers. Extensions may also change their behavior to\n facilitate easier testing. You should enable this in your own tests.\n\n Default: ``False``\n\n.. py:data:: PROPAGATE_EXCEPTIONS\n\n Exceptions are re-raised rather than being handled by the app's error\n handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``\n is enabled.\n\n Default: ``None``\n\n.. py:data:: TRAP_HTTP_EXCEPTIONS\n\n If there is no handler for an ``HTTPException``-type exception, re-raise it\n to be handled by the interactive debugger instead of returning it as a\n simple error response.\n\n Default: ``False``\n\n.. py:data:: TRAP_BAD_REQUEST_ERRORS\n\n Trying to access a key that doesn't exist from request dicts like ``args``\n and ``form`` will return a 400 Bad Request error page. Enable this to treat\n the error as an unhandled exception instead so that you get the interactive\n debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If\n unset, it is enabled in debug mode.\n\n Default: ``None``\n\n.. py:data:: SECRET_KEY\n\n A secret key that will be used for securely signing the session cookie\n and can be used for any other security related needs by extensions or your\n application. It should be a long random ``bytes`` or ``str``. For\n example, copy the output of this to your config::\n\n $ python -c 'import secrets; print(secrets.token_hex())'\n '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'\n\n **Do not reveal the secret key when posting questions or committing code.**\n\n Default: ``None``\n\n.. py:data:: SESSION_COOKIE_NAME\n\n The name of the session cookie. Can be changed in case you already have a\n cookie with the same name.\n\n Default: ``'session'``\n\n.. py:data:: SESSION_COOKIE_DOMAIN\n\n The value of the ``Domain`` parameter on the session cookie. If not set, browsers\n will only send the cookie to the exact domain it was set from. Otherwise, they\n will send it to any subdomain of the given value as well.\n\n Not setting this value is more restricted and secure than setting it.\n\n Default: ``None``\n\n .. versionchanged:: 2.3\n Not set by default, does not fall back to ``SERVER_NAME``.\n\n.. py:data:: SESSION_COOKIE_PATH\n\n The path that the session cookie will be valid for. If not set, the cookie\n will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.\n\n Default: ``None``\n\n.. py:data:: SESSION_COOKIE_HTTPONLY\n\n Browsers will not allow JavaScript access to cookies marked as \"HTTP only\"\n for security.\n\n Default: ``True``\n\n.. py:data:: SESSION_COOKIE_SECURE\n\n Browsers will only send cookies with requests over HTTPS if the cookie is\n marked \"secure\". The application must be served over HTTPS for this to make\n sense.\n\n Default: ``False``\n\n.. py:data:: SESSION_COOKIE_SAMESITE\n\n Restrict how cookies are sent with requests from external sites. Can\n be set to ``'Lax'`` (recommended) or ``'Strict'``.\n See :ref:`security-cookie`.\n\n Default: ``None``\n\n .. versionadded:: 1.0\n\n.. py:data:: PERMANENT_SESSION_LIFETIME\n\n If ``session.permanent`` is true, the cookie's expiration will be set this\n number of seconds in the future. Can either be a\n :class:`datetime.timedelta` or an ``int``.\n\n Flask's default cookie implementation validates that the cryptographic\n signature is not older than this value.\n\n Default: ``timedelta(days=31)`` (``2678400`` seconds)\n\n.. py:data:: SESSION_REFRESH_EACH_REQUEST\n\n Control whether the cookie is sent with every response when\n ``session.permanent`` is true. Sending the cookie every time (the default)\n can more reliably keep the session from expiring, but uses more bandwidth.\n Non-permanent sessions are not affected.\n\n Default: ``True``\n\n.. py:data:: USE_X_SENDFILE\n\n When serving files, set the ``X-Sendfile`` header instead of serving the\n data with Flask. Some web servers, such as Apache, recognize this and serve\n the data more efficiently. This only makes sense when using such a server.\n\n Default: ``False``\n\n.. py:data:: SEND_FILE_MAX_AGE_DEFAULT\n\n When serving files, set the cache control max age to this number of\n seconds. Can be a :class:`datetime.timedelta` or an ``int``.\n Override this value on a per-file basis using\n :meth:`~flask.Flask.get_send_file_max_age` on the application or\n blueprint.\n\n If ``None``, ``send_file`` tells the browser to use conditional\n requests will be used instead of a timed cache, which is usually\n preferable.\n\n Default: ``None``\n\n.. py:data:: SERVER_NAME\n\n Inform the application what host and port it is bound to. Required\n for subdomain route matching support.\n\n If set, ``url_for`` can generate external URLs with only an application\n context instead of a request context.\n\n Default: ``None``\n\n .. versionchanged:: 2.3\n Does not affect ``SESSION_COOKIE_DOMAIN``.\n\n.. py:data:: APPLICATION_ROOT\n\n Inform the application what path it is mounted under by the application /\n web server. This is used for generating URLs outside the context of a\n request (inside a request, the dispatcher is responsible for setting\n ``SCRIPT_NAME`` instead; see :doc:`/patterns/appdispatch`\n for examples of dispatch configuration).\n\n Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not\n set.\n\n Default: ``'/'``\n\n.. py:data:: PREFERRED_URL_SCHEME\n\n Use this scheme for generating external URLs when not in a request context.\n\n Default: ``'http'``\n\n.. py:data:: MAX_CONTENT_LENGTH\n\n Don't read more than this many bytes from the incoming request data. If not\n set and the request does not specify a ``CONTENT_LENGTH``, no data will be\n read for security.\n\n Default: ``None``\n\n.. py:data:: TEMPLATES_AUTO_RELOAD\n\n Reload templates when they are changed. If not set, it will be enabled in\n debug mode.\n\n Default: ``None``\n\n.. py:data:: EXPLAIN_TEMPLATE_LOADING\n\n Log debugging information tracing how a template file was loaded. This can\n be useful to figure out why a template was not loaded or the wrong file\n appears to be loaded.\n\n Default: ``False``\n\n.. py:data:: MAX_COOKIE_SIZE\n\n Warn if cookie headers are larger than this many bytes. Defaults to\n ``4093``. Larger cookies may be silently ignored by browsers. Set to\n ``0`` to disable the warning.\n\n.. versionadded:: 0.4\n ``LOGGER_NAME``\n\n.. versionadded:: 0.5\n ``SERVER_NAME``\n\n.. versionadded:: 0.6\n ``MAX_CONTENT_LENGTH``\n\n.. versionadded:: 0.7\n ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``\n\n.. versionadded:: 0.8\n ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,\n ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,\n ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,\n ``SESSION_COOKIE_SECURE``\n\n.. versionadded:: 0.9\n ``PREFERRED_URL_SCHEME``\n\n.. versionadded:: 0.10\n ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``\n\n.. versionadded:: 0.11\n ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,\n ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``\n\n.. versionchanged:: 1.0\n ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See\n :doc:`/logging` for information about configuration.\n\n Added :data:`ENV` to reflect the :envvar:`FLASK_ENV` environment\n variable.\n\n Added :data:`SESSION_COOKIE_SAMESITE` to control the session\n cookie's ``SameSite`` option.\n\n Added :data:`MAX_COOKIE_SIZE` to control a warning from Werkzeug.\n\n.. versionchanged:: 2.2\n Removed ``PRESERVE_CONTEXT_ON_EXCEPTION``.\n\n.. versionchanged:: 2.3\n ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_MIMETYPE``, and\n ``JSONIFY_PRETTYPRINT_REGULAR`` were removed. The default ``app.json`` provider has\n equivalent attributes instead.\n\n.. versionchanged:: 2.3\n ``ENV`` was removed.\n\n\nConfiguring from Python Files\n-----------------------------\n\nConfiguration becomes more useful if you can store it in a separate file, ideally\nlocated outside the actual application package. You can deploy your application, then\nseparately configure it for the specific deployment.\n\nA common pattern is this::\n\n app = Flask(__name__)\n app.config.from_object('yourapplication.default_settings')\n app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\nThis first loads the configuration from the\n`yourapplication.default_settings` module and then overrides the values\nwith the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`\nenvironment variable points to. This environment variable can be set\nin the shell before starting the server:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg\n $ flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: Fish\n\n .. code-block:: text\n\n $ set -x YOURAPPLICATION_SETTINGS /path/to/settings.cfg\n $ flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set YOURAPPLICATION_SETTINGS=\\path\\to\\settings.cfg\n > flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:YOURAPPLICATION_SETTINGS = \"\\path\\to\\settings.cfg\"\n > flask run\n * Running on http://127.0.0.1:5000/\n\nThe configuration files themselves are actual Python files. Only values\nin uppercase are actually stored in the config object later on. So make\nsure to use uppercase letters for your config keys.\n\nHere is an example of a configuration file::\n\n # Example configuration\n SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'\n\nMake sure to load the configuration very early on, so that extensions have\nthe ability to access the configuration when starting up. There are other\nmethods on the config object as well to load from individual files. For a\ncomplete reference, read the :class:`~flask.Config` object's\ndocumentation.\n\n\nConfiguring from Data Files\n---------------------------\n\nIt is also possible to load configuration from a file in a format of\nyour choice using :meth:`~flask.Config.from_file`. For example to load\nfrom a TOML file:\n\n.. code-block:: python\n\n import toml\n app.config.from_file(\"config.toml\", load=toml.load)\n\nOr from a JSON file:\n\n.. code-block:: python\n\n import json\n app.config.from_file(\"config.json\", load=json.load)\n\n\nConfiguring from Environment Variables\n--------------------------------------\n\nIn addition to pointing to configuration files using environment\nvariables, you may find it useful (or necessary) to control your\nconfiguration values directly from the environment. Flask can be\ninstructed to load all environment variables starting with a specific\nprefix into the config using :meth:`~flask.Config.from_prefixed_env`.\n\nEnvironment variables can be set in the shell before starting the\nserver:\n\n.. tabs::\n\n .. group-tab:: Bash\n\n .. code-block:: text\n\n $ export FLASK_SECRET_KEY=\"5f352379324c22463451387a0aec5d2f\"\n $ export FLASK_MAIL_ENABLED=false\n $ flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: Fish\n\n .. code-block:: text\n\n $ set -x FLASK_SECRET_KEY \"5f352379324c22463451387a0aec5d2f\"\n $ set -x FLASK_MAIL_ENABLED false\n $ flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: CMD\n\n .. code-block:: text\n\n > set FLASK_SECRET_KEY=\"5f352379324c22463451387a0aec5d2f\"\n > set FLASK_MAIL_ENABLED=false\n > flask run\n * Running on http://127.0.0.1:5000/\n\n .. group-tab:: Powershell\n\n .. code-block:: text\n\n > $env:FLASK_SECRET_KEY = \"5f352379324c22463451387a0aec5d2f\"\n > $env:FLASK_MAIL_ENABLED = \"false\"\n > flask run\n * Running on http://127.0.0.1:5000/\n\nThe variables can then be loaded and accessed via the config with a key\nequal to the environment variable name without the prefix i.e.\n\n.. code-block:: python\n\n app.config.from_prefixed_env()\n app.config[\"SECRET_KEY\"] # Is \"5f352379324c22463451387a0aec5d2f\"\n\nThe prefix is ``FLASK_`` by default. This is configurable via the\n``prefix`` argument of :meth:`~flask.Config.from_prefixed_env`.\n\nValues will be parsed to attempt to convert them to a more specific type\nthan strings. By default :func:`json.loads` is used, so any valid JSON\nvalue is possible, including lists and dicts. This is configurable via\nthe ``loads`` argument of :meth:`~flask.Config.from_prefixed_env`.\n\nWhen adding a boolean value with the default JSON parsing, only \"true\"\nand \"false\", lowercase, are valid values. Keep in mind that any\nnon-empty string is considered ``True`` by Python.\n\nIt is possible to set keys in nested dictionaries by separating the\nkeys with double underscore (``__``). Any intermediate keys that don't\nexist on the parent dict will be initialized to an empty dict.\n\n.. code-block:: text\n\n $ export FLASK_MYAPI__credentials__username=user123\n\n.. code-block:: python\n\n app.config[\"MYAPI\"][\"credentials\"][\"username\"] # Is \"user123\"\n\nOn Windows, environment variable keys are always uppercase, therefore\nthe above example would end up as ``MYAPI__CREDENTIALS__USERNAME``.\n\nFor even more config loading features, including merging and\ncase-insensitive Windows support, try a dedicated library such as\nDynaconf_, which includes integration with Flask.\n\n.. _Dynaconf: https://www.dynaconf.com/\n\n\nConfiguration Best Practices\n----------------------------\n\nThe downside with the approach mentioned earlier is that it makes testing\na little harder. There is no single 100% solution for this problem in\ngeneral, but there are a couple of things you can keep in mind to improve\nthat experience:\n\n1. Create your application in a function and register blueprints on it.\n That way you can create multiple instances of your application with\n different configurations attached which makes unit testing a lot\n easier. You can use this to pass in configuration as needed.\n\n2. Do not write code that needs the configuration at import time. If you\n limit yourself to request-only accesses to the configuration you can\n reconfigure the object later on as needed.\n\n3. Make sure to load the configuration very early on, so that\n extensions can access the configuration when calling ``init_app``.\n\n\n.. _config-dev-prod:\n\nDevelopment / Production\n------------------------\n\nMost applications need more than one configuration. There should be at\nleast separate configurations for the production server and the one used\nduring development. The easiest way to handle this is to use a default\nconfiguration that is always loaded and part of the version control, and a\nseparate configuration that overrides the values as necessary as mentioned\nin the example above::\n\n app = Flask(__name__)\n app.config.from_object('yourapplication.default_settings')\n app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\nThen you just have to add a separate :file:`config.py` file and export\n``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However\nthere are alternative ways as well. For example you could use imports or\nsubclassing.\n\nWhat is very popular in the Django world is to make the import explicit in\nthe config file by adding ``from yourapplication.default_settings\nimport *`` to the top of the file and then overriding the changes by hand.\nYou could also inspect an environment variable like\n``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc\nand import different hard-coded files based on that.\n\nAn interesting pattern is also to use classes and inheritance for\nconfiguration::\n\n class Config(object):\n TESTING = False\n\n class ProductionConfig(Config):\n DATABASE_URI = 'mysql://user@localhost/foo'\n\n class DevelopmentConfig(Config):\n DATABASE_URI = \"sqlite:////tmp/foo.db\"\n\n class TestingConfig(Config):\n DATABASE_URI = 'sqlite:///:memory:'\n TESTING = True\n\nTo enable such a config you just have to call into\n:meth:`~flask.Config.from_object`::\n\n app.config.from_object('configmodule.ProductionConfig')\n\nNote that :meth:`~flask.Config.from_object` does not instantiate the class\nobject. If you need to instantiate the class, such as to access a property,\nthen you must do so before calling :meth:`~flask.Config.from_object`::\n\n from configmodule import ProductionConfig\n app.config.from_object(ProductionConfig())\n\n # Alternatively, import via string:\n from werkzeug.utils import import_string\n cfg = import_string('configmodule.ProductionConfig')()\n app.config.from_object(cfg)\n\nInstantiating the configuration object allows you to use ``@property`` in\nyour configuration classes::\n\n class Config(object):\n \"\"\"Base config, uses staging database server.\"\"\"\n TESTING = False\n DB_SERVER = '192.168.1.56'\n\n @property\n def DATABASE_URI(self): # Note: all caps\n return f\"mysql://user@{self.DB_SERVER}/foo\"\n\n class ProductionConfig(Config):\n \"\"\"Uses production database server.\"\"\"\n DB_SERVER = '192.168.19.32'\n\n class DevelopmentConfig(Config):\n DB_SERVER = 'localhost'\n\n class TestingConfig(Config):\n DB_SERVER = 'localhost'\n DATABASE_URI = 'sqlite:///:memory:'\n\nThere are many different ways and it's up to you how you want to manage\nyour configuration files. However here a list of good recommendations:\n\n- Keep a default configuration in version control. Either populate the\n config with this default configuration or import it in your own\n configuration files before overriding values.\n- Use an environment variable to switch between the configurations.\n This can be done from outside the Python interpreter and makes\n development and deployment much easier because you can quickly and\n easily switch between different configs without having to touch the\n code at all. If you are working often on different projects you can\n even create your own script for sourcing that activates a virtualenv\n and exports the development configuration for you.\n- Use a tool like `fabric`_ to push code and configuration separately\n to the production server(s).\n\n.. _fabric: https://www.fabfile.org/\n\n\n.. _instance-folders:\n\nInstance Folders\n----------------\n\n.. versionadded:: 0.8\n\nFlask 0.8 introduces instance folders. Flask for a long time made it\npossible to refer to paths relative to the application's folder directly\n(via :attr:`Flask.root_path`). This was also how many developers loaded\nconfigurations stored next to the application. Unfortunately however this\nonly works well if applications are not packages in which case the root\npath refers to the contents of the package.\n\nWith Flask 0.8 a new attribute was introduced:\n:attr:`Flask.instance_path`. It refers to a new concept called the\n“instance folder”. The instance folder is designed to not be under\nversion control and be deployment specific. It's the perfect place to\ndrop things that either change at runtime or configuration files.\n\nYou can either explicitly provide the path of the instance folder when\ncreating the Flask application or you can let Flask autodetect the\ninstance folder. For explicit configuration use the `instance_path`\nparameter::\n\n app = Flask(__name__, instance_path='/path/to/instance/folder')\n\nPlease keep in mind that this path *must* be absolute when provided.\n\nIf the `instance_path` parameter is not provided the following default\nlocations are used:\n\n- Uninstalled module::\n\n /myapp.py\n /instance\n\n- Uninstalled package::\n\n /myapp\n /__init__.py\n /instance\n\n- Installed module or package::\n\n $PREFIX/lib/pythonX.Y/site-packages/myapp\n $PREFIX/var/myapp-instance\n\n ``$PREFIX`` is the prefix of your Python installation. This can be\n ``/usr`` or the path to your virtualenv. You can print the value of\n ``sys.prefix`` to see what the prefix is set to.\n\nSince the config object provided loading of configuration files from\nrelative filenames we made it possible to change the loading via filenames\nto be relative to the instance path if wanted. The behavior of relative\npaths in config files can be flipped between “relative to the application\nroot” (the default) to “relative to instance folder” via the\n`instance_relative_config` switch to the application constructor::\n\n app = Flask(__name__, instance_relative_config=True)\n\nHere is a full example of how to configure Flask to preload the config\nfrom a module and then override the config from a file in the instance\nfolder if it exists::\n\n app = Flask(__name__, instance_relative_config=True)\n app.config.from_object('yourapplication.default_settings')\n app.config.from_pyfile('application.cfg', silent=True)\n\nThe path to the instance folder can be found via the\n:attr:`Flask.instance_path`. Flask also provides a shortcut to open a\nfile from the instance folder with :meth:`Flask.open_instance_resource`.\n\nExample usage for both::\n\n filename = os.path.join(app.instance_path, 'application.cfg')\n with open(filename) as f:\n config = f.read()\n\n # or via open_instance_resource:\n with app.open_instance_resource('application.cfg') as f:\n config = f.read()\n"},{"col":4,"comment":"null","endLoc":162,"header":"def test_url_with_method(self, app, req_ctx)","id":1009,"name":"test_url_with_method","nodeType":"Function","startLoc":143,"text":"def test_url_with_method(self, app, req_ctx):\n from flask.views import MethodView\n\n class MyView(MethodView):\n def get(self, id=None):\n if id is None:\n return \"List\"\n return f\"Get {id:d}\"\n\n def post(self):\n return \"Create\"\n\n myview = MyView.as_view(\"myview\")\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/\", methods=[\"GET\"], view_func=myview)\n app.add_url_rule(\"/myview/create\", methods=[\"POST\"], view_func=myview)\n\n assert flask.url_for(\"myview\", _method=\"GET\") == \"/myview/\"\n assert flask.url_for(\"myview\", id=42, _method=\"GET\") == \"/myview/42\"\n assert flask.url_for(\"myview\", _method=\"POST\") == \"/myview/create\""},{"col":0,"comment":"null","endLoc":181,"header":"def test_appcontext_tearing_down_signal(app, client)","id":1011,"name":"test_appcontext_tearing_down_signal","nodeType":"Function","startLoc":163,"text":"def test_appcontext_tearing_down_signal(app, client):\n app.testing = False\n recorded = []\n\n def record_teardown(sender, exc):\n recorded.append(exc)\n\n @app.route(\"/\")\n def index():\n 1 // 0\n\n flask.appcontext_tearing_down.connect(record_teardown, app)\n try:\n rv = client.get(\"/\")\n assert rv.status_code == 500\n assert len(recorded) == 1\n assert isinstance(recorded[0], ZeroDivisionError)\n finally:\n flask.appcontext_tearing_down.disconnect(record_teardown, app)"},{"className":"Request","col":0,"comment":"The request object used by default in Flask. Remembers the\n matched endpoint and view arguments.\n\n It is what ends up as :class:`~flask.request`. If you want to replace\n the request object used you can subclass this and set\n :attr:`~flask.Flask.request_class` to your subclass.\n\n The request object is a :class:`~werkzeug.wrappers.Request` subclass and\n provides all of the attributes Werkzeug defines plus a few Flask\n specific ones.\n ","endLoc":133,"id":1013,"nodeType":"Class","startLoc":15,"text":"class Request(RequestBase):\n \"\"\"The request object used by default in Flask. Remembers the\n matched endpoint and view arguments.\n\n It is what ends up as :class:`~flask.request`. If you want to replace\n the request object used you can subclass this and set\n :attr:`~flask.Flask.request_class` to your subclass.\n\n The request object is a :class:`~werkzeug.wrappers.Request` subclass and\n provides all of the attributes Werkzeug defines plus a few Flask\n specific ones.\n \"\"\"\n\n json_module: t.Any = json\n\n #: The internal URL rule that matched the request. This can be\n #: useful to inspect which methods are allowed for the URL from\n #: a before/after handler (``request.url_rule.methods``) etc.\n #: Though if the request's method was invalid for the URL rule,\n #: the valid list is available in ``routing_exception.valid_methods``\n #: instead (an attribute of the Werkzeug exception\n #: :exc:`~werkzeug.exceptions.MethodNotAllowed`)\n #: because the request was never internally bound.\n #:\n #: .. versionadded:: 0.6\n url_rule: t.Optional[\"Rule\"] = None\n\n #: A dict of view arguments that matched the request. If an exception\n #: happened when matching, this will be ``None``.\n view_args: t.Optional[t.Dict[str, t.Any]] = None\n\n #: If matching the URL failed, this is the exception that will be\n #: raised / was raised as part of the request handling. This is\n #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or\n #: something similar.\n routing_exception: t.Optional[Exception] = None\n\n @property\n def max_content_length(self) -> t.Optional[int]: # type: ignore\n \"\"\"Read-only view of the ``MAX_CONTENT_LENGTH`` config key.\"\"\"\n if current_app:\n return current_app.config[\"MAX_CONTENT_LENGTH\"]\n else:\n return None\n\n @property\n def endpoint(self) -> t.Optional[str]:\n \"\"\"The endpoint that matched the request URL.\n\n This will be ``None`` if matching failed or has not been\n performed yet.\n\n This in combination with :attr:`view_args` can be used to\n reconstruct the same URL or a modified URL.\n \"\"\"\n if self.url_rule is not None:\n return self.url_rule.endpoint\n\n return None\n\n @property\n def blueprint(self) -> t.Optional[str]:\n \"\"\"The registered name of the current blueprint.\n\n This will be ``None`` if the endpoint is not part of a\n blueprint, or if URL matching failed or has not been performed\n yet.\n\n This does not necessarily match the name the blueprint was\n created with. It may have been nested, or registered with a\n different name.\n \"\"\"\n endpoint = self.endpoint\n\n if endpoint is not None and \".\" in endpoint:\n return endpoint.rpartition(\".\")[0]\n\n return None\n\n @property\n def blueprints(self) -> t.List[str]:\n \"\"\"The registered names of the current blueprint upwards through\n parent blueprints.\n\n This will be an empty list if there is no current blueprint, or\n if URL matching failed.\n\n .. versionadded:: 2.0.1\n \"\"\"\n name = self.blueprint\n\n if name is None:\n return []\n\n return _split_blueprint_path(name)\n\n def _load_form_data(self) -> None:\n super()._load_form_data()\n\n # In debug mode we're replacing the files multidict with an ad-hoc\n # subclass that raises a different error for key errors.\n if (\n current_app\n and current_app.debug\n and self.mimetype != \"multipart/form-data\"\n and not self.files\n ):\n from .debughelpers import attach_enctype_error_multidict\n\n attach_enctype_error_multidict(self)\n\n def on_json_loading_failed(self, e: t.Optional[ValueError]) -> t.Any:\n try:\n return super().on_json_loading_failed(e)\n except BadRequest as e:\n if current_app and current_app.debug:\n raise\n\n raise BadRequest() from e"},{"col":4,"comment":"Read-only view of the ``MAX_CONTENT_LENGTH`` config key.","endLoc":58,"header":"@property\n def max_content_length(self) -> t.Optional[int]","id":1014,"name":"max_content_length","nodeType":"Function","startLoc":52,"text":"@property\n def max_content_length(self) -> t.Optional[int]: # type: ignore\n \"\"\"Read-only view of the ``MAX_CONTENT_LENGTH`` config key.\"\"\"\n if current_app:\n return current_app.config[\"MAX_CONTENT_LENGTH\"]\n else:\n return None"},{"col":4,"comment":"The endpoint that matched the request URL.\n\n This will be ``None`` if matching failed or has not been\n performed yet.\n\n This in combination with :attr:`view_args` can be used to\n reconstruct the same URL or a modified URL.\n ","endLoc":73,"header":"@property\n def endpoint(self) -> t.Optional[str]","id":1015,"name":"endpoint","nodeType":"Function","startLoc":60,"text":"@property\n def endpoint(self) -> t.Optional[str]:\n \"\"\"The endpoint that matched the request URL.\n\n This will be ``None`` if matching failed or has not been\n performed yet.\n\n This in combination with :attr:`view_args` can be used to\n reconstruct the same URL or a modified URL.\n \"\"\"\n if self.url_rule is not None:\n return self.url_rule.endpoint\n\n return None"},{"col":4,"comment":"The registered name of the current blueprint.\n\n This will be ``None`` if the endpoint is not part of a\n blueprint, or if URL matching failed or has not been performed\n yet.\n\n This does not necessarily match the name the blueprint was\n created with. It may have been nested, or registered with a\n different name.\n ","endLoc":92,"header":"@property\n def blueprint(self) -> t.Optional[str]","id":1016,"name":"blueprint","nodeType":"Function","startLoc":75,"text":"@property\n def blueprint(self) -> t.Optional[str]:\n \"\"\"The registered name of the current blueprint.\n\n This will be ``None`` if the endpoint is not part of a\n blueprint, or if URL matching failed or has not been performed\n yet.\n\n This does not necessarily match the name the blueprint was\n created with. It may have been nested, or registered with a\n different name.\n \"\"\"\n endpoint = self.endpoint\n\n if endpoint is not None and \".\" in endpoint:\n return endpoint.rpartition(\".\")[0]\n\n return None"},{"id":1017,"name":"pyproject.toml","nodeType":"TextFile","path":"examples/javascript","text":"[project]\nname = \"js_example\"\nversion = \"1.1.0\"\ndescription = \"Demonstrates making AJAX requests to Flask.\"\nreadme = \"README.rst\"\nlicense = {text = \"BSD-3-Clause\"}\nmaintainers = [{name = \"Pallets\", email = \"contact@palletsprojects.com\"}]\ndependencies = [\"flask\"]\n\n[project.urls]\nDocumentation = \"https://flask.palletsprojects.com/patterns/jquery/\"\n\n[project.optional-dependencies]\ntest = [\"pytest\"]\n\n[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\nfilterwarnings = [\"error\"]\n\n[tool.coverage.run]\nbranch = true\nsource = [\"js_example\", \"tests\"]\n"},{"attributeType":"dict","col":4,"comment":"null","endLoc":92,"id":1018,"name":"__dict__","nodeType":"Attribute","startLoc":92,"text":"__dict__"},{"attributeType":"null","col":4,"comment":"null","endLoc":156,"id":1019,"name":"json_module","nodeType":"Attribute","startLoc":156,"text":"json_module"},{"col":4,"comment":"null","endLoc":95,"header":"@overload\n def __new__(cls, attr: str) -> attrgetter[Any]","id":1020,"name":"__new__","nodeType":"Function","startLoc":94,"text":"@overload\n def __new__(cls, attr: str) -> attrgetter[Any]: ..."},{"col":4,"comment":"null","endLoc":97,"header":"@overload\n def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]","id":1021,"name":"__new__","nodeType":"Function","startLoc":96,"text":"@overload\n def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ..."},{"col":4,"comment":"null","endLoc":462,"header":"@pytest.fixture\n def invoke_no_routes(self, runner)","id":1022,"name":"invoke_no_routes","nodeType":"Function","startLoc":453,"text":"@pytest.fixture\n def invoke_no_routes(self, runner):\n def create_app():\n app = Flask(__name__, static_folder=None)\n app.testing = True\n\n return app\n\n cli = FlaskGroup(create_app=create_app)\n return partial(runner.invoke, cli)"},{"col":4,"comment":"null","endLoc":99,"header":"@overload\n def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]","id":1023,"name":"__new__","nodeType":"Function","startLoc":98,"text":"@overload\n def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ..."},{"col":4,"comment":"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n ","endLoc":284,"header":"def register(\n self,\n tag_class: t.Type[JSONTag],\n force: bool = False,\n index: t.Optional[int] = None,\n ) -> None","id":1024,"name":"register","nodeType":"Function","startLoc":253,"text":"def register(\n self,\n tag_class: t.Type[JSONTag],\n force: bool = False,\n index: t.Optional[int] = None,\n ) -> None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n \"\"\"\n tag = tag_class(self)\n key = tag.key\n\n if key is not None:\n if not force and key in self.tags:\n raise KeyError(f\"Tag '{key}' is already registered.\")\n\n self.tags[key] = tag\n\n if index is None:\n self.order.append(tag)\n else:\n self.order.insert(index, tag)"},{"col":4,"comment":"null","endLoc":101,"header":"@overload\n def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]","id":1025,"name":"__new__","nodeType":"Function","startLoc":100,"text":"@overload\n def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ..."},{"col":4,"comment":"null","endLoc":103,"header":"@overload\n def __new__(cls, attr: str, *attrs: str) -> attrgetter[tuple[Any, ...]]","id":1026,"name":"__new__","nodeType":"Function","startLoc":102,"text":"@overload\n def __new__(cls, attr: str, *attrs: str) -> attrgetter[tuple[Any, ...]]: ..."},{"col":4,"comment":"null","endLoc":104,"header":"def __call__(self, obj: Any) -> _T_co","id":1027,"name":"__call__","nodeType":"Function","startLoc":104,"text":"def __call__(self, obj: Any) -> _T_co: ..."},{"className":"TestNoImports","col":0,"comment":"Test Flasks are created without import.\n\n Avoiding ``__import__`` helps create Flask instances where there are errors\n at import time. Those runtime errors will be apparent to the user soon\n enough, but tools which build Flask instances meta-programmatically benefit\n from a Flask which does not ``__import__``. Instead of importing to\n retrieve file paths or metadata on a module or package, use the pkgutil and\n imp modules in the Python standard library.\n ","endLoc":226,"id":1028,"nodeType":"Class","startLoc":210,"text":"class TestNoImports:\n \"\"\"Test Flasks are created without import.\n\n Avoiding ``__import__`` helps create Flask instances where there are errors\n at import time. Those runtime errors will be apparent to the user soon\n enough, but tools which build Flask instances meta-programmatically benefit\n from a Flask which does not ``__import__``. Instead of importing to\n retrieve file paths or metadata on a module or package, use the pkgutil and\n imp modules in the Python standard library.\n \"\"\"\n\n def test_name_with_import_error(self, modules_tmpdir):\n modules_tmpdir.join(\"importerror.py\").write(\"raise NotImplementedError()\")\n try:\n flask.Flask(\"importerror\")\n except NotImplementedError:\n AssertionError(\"Flask(import_name) is importing import_name.\")"},{"col":4,"comment":"null","endLoc":226,"header":"def test_name_with_import_error(self, modules_tmpdir)","id":1029,"name":"test_name_with_import_error","nodeType":"Function","startLoc":221,"text":"def test_name_with_import_error(self, modules_tmpdir):\n modules_tmpdir.join(\"importerror.py\").write(\"raise NotImplementedError()\")\n try:\n flask.Flask(\"importerror\")\n except NotImplementedError:\n AssertionError(\"Flask(import_name) is importing import_name.\")"},{"attributeType":"null","col":4,"comment":"null","endLoc":158,"id":1030,"name":"autocorrect_location_header","nodeType":"Attribute","startLoc":158,"text":"autocorrect_location_header"},{"fileName":"conftest.py","filePath":"tests","id":1031,"nodeType":"File","text":"import os\nimport pkgutil\nimport sys\nimport textwrap\n\nimport pytest\nfrom _pytest import monkeypatch\n\nfrom flask import Flask\nfrom flask.globals import request_ctx\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef _standard_os_environ():\n \"\"\"Set up ``os.environ`` at the start of the test session to have\n standard values. Returns a list of operations that is used by\n :func:`._reset_os_environ` after each test.\n \"\"\"\n mp = monkeypatch.MonkeyPatch()\n out = (\n (os.environ, \"FLASK_ENV_FILE\", monkeypatch.notset),\n (os.environ, \"FLASK_APP\", monkeypatch.notset),\n (os.environ, \"FLASK_DEBUG\", monkeypatch.notset),\n (os.environ, \"FLASK_RUN_FROM_CLI\", monkeypatch.notset),\n (os.environ, \"WERKZEUG_RUN_MAIN\", monkeypatch.notset),\n )\n\n for _, key, value in out:\n if value is monkeypatch.notset:\n mp.delenv(key, False)\n else:\n mp.setenv(key, value)\n\n yield out\n mp.undo()\n\n\n@pytest.fixture(autouse=True)\ndef _reset_os_environ(monkeypatch, _standard_os_environ):\n \"\"\"Reset ``os.environ`` to the standard environ after each test,\n in case a test changed something without cleaning up.\n \"\"\"\n monkeypatch._setitem.extend(_standard_os_environ)\n\n\n@pytest.fixture\ndef app():\n app = Flask(\"flask_test\", root_path=os.path.dirname(__file__))\n app.config.update(\n TESTING=True,\n SECRET_KEY=\"test key\",\n )\n return app\n\n\n@pytest.fixture\ndef app_ctx(app):\n with app.app_context() as ctx:\n yield ctx\n\n\n@pytest.fixture\ndef req_ctx(app):\n with app.test_request_context() as ctx:\n yield ctx\n\n\n@pytest.fixture\ndef client(app):\n return app.test_client()\n\n\n@pytest.fixture\ndef test_apps(monkeypatch):\n monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), \"test_apps\"))\n original_modules = set(sys.modules.keys())\n\n yield\n\n # Remove any imports cached during the test. Otherwise \"import app\"\n # will work in the next test even though it's no longer on the path.\n for key in sys.modules.keys() - original_modules:\n sys.modules.pop(key)\n\n\n@pytest.fixture(autouse=True)\ndef leak_detector():\n yield\n\n # make sure we're not leaking a request context since we are\n # testing flask internally in debug mode in a few cases\n leaks = []\n while request_ctx:\n leaks.append(request_ctx._get_current_object())\n request_ctx.pop()\n\n assert leaks == []\n\n\n@pytest.fixture(params=(True, False))\ndef limit_loader(request, monkeypatch):\n \"\"\"Patch pkgutil.get_loader to give loader without get_filename or archive.\n\n This provides for tests where a system has custom loaders, e.g. Google App\n Engine's HardenedModulesHook, which have neither the `get_filename` method\n nor the `archive` attribute.\n\n This fixture will run the testcase twice, once with and once without the\n limitation/mock.\n \"\"\"\n if not request.param:\n return\n\n class LimitedLoader:\n def __init__(self, loader):\n self.loader = loader\n\n def __getattr__(self, name):\n if name in {\"archive\", \"get_filename\"}:\n raise AttributeError(f\"Mocking a loader which does not have {name!r}.\")\n return getattr(self.loader, name)\n\n old_get_loader = pkgutil.get_loader\n\n def get_loader(*args, **kwargs):\n return LimitedLoader(old_get_loader(*args, **kwargs))\n\n monkeypatch.setattr(pkgutil, \"get_loader\", get_loader)\n\n\n@pytest.fixture\ndef modules_tmpdir(tmpdir, monkeypatch):\n \"\"\"A tmpdir added to sys.path.\"\"\"\n rv = tmpdir.mkdir(\"modules_tmpdir\")\n monkeypatch.syspath_prepend(str(rv))\n return rv\n\n\n@pytest.fixture\ndef modules_tmpdir_prefix(modules_tmpdir, monkeypatch):\n monkeypatch.setattr(sys, \"prefix\", str(modules_tmpdir))\n return modules_tmpdir\n\n\n@pytest.fixture\ndef site_packages(modules_tmpdir, monkeypatch):\n \"\"\"Create a fake site-packages.\"\"\"\n rv = (\n modules_tmpdir.mkdir(\"lib\")\n .mkdir(f\"python{sys.version_info.major}.{sys.version_info.minor}\")\n .mkdir(\"site-packages\")\n )\n monkeypatch.syspath_prepend(str(rv))\n return rv\n\n\n@pytest.fixture\ndef install_egg(modules_tmpdir, monkeypatch):\n \"\"\"Generate egg from package name inside base and put the egg into\n sys.path.\"\"\"\n\n def inner(name, base=modules_tmpdir):\n base.join(name).ensure_dir()\n base.join(name).join(\"__init__.py\").ensure()\n\n egg_setup = base.join(\"setup.py\")\n egg_setup.write(\n textwrap.dedent(\n f\"\"\"\n from setuptools import setup\n setup(\n name=\"{name}\",\n version=\"1.0\",\n packages=[\"site_egg\"],\n zip_safe=True,\n )\n \"\"\"\n )\n )\n\n import subprocess\n\n subprocess.check_call(\n [sys.executable, \"setup.py\", \"bdist_egg\"], cwd=str(modules_tmpdir)\n )\n (egg_path,) = modules_tmpdir.join(\"dist/\").listdir()\n monkeypatch.syspath_prepend(str(egg_path))\n return egg_path\n\n return inner\n\n\n@pytest.fixture\ndef purge_module(request):\n def inner(name):\n request.addfinalizer(lambda: sys.modules.pop(name, None))\n\n return inner\n"},{"col":0,"comment":"null","endLoc":44,"header":"def test_uninstalled_package_paths(modules_tmpdir, purge_module)","id":1032,"name":"test_uninstalled_package_paths","nodeType":"Function","startLoc":31,"text":"def test_uninstalled_package_paths(modules_tmpdir, purge_module):\n app = modules_tmpdir.mkdir(\"config_package_app\")\n init = app.join(\"__init__.py\")\n init.write(\n \"import os\\n\"\n \"import flask\\n\"\n \"here = os.path.abspath(os.path.dirname(__file__))\\n\"\n \"app = flask.Flask(__name__)\\n\"\n )\n purge_module(\"config_package_app\")\n\n from config_package_app import app\n\n assert app.instance_path == str(modules_tmpdir.join(\"instance\"))"},{"col":0,"comment":"null","endLoc":27,"header":"def test_teardown_on_pop(app)","id":1033,"name":"test_teardown_on_pop","nodeType":"Function","startLoc":16,"text":"def test_teardown_on_pop(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n ctx = app.test_request_context()\n ctx.push()\n assert buffer == []\n ctx.pop()\n assert buffer == [None]"},{"id":1034,"name":"tests/test_apps/subdomaintestmodule/static","nodeType":"Package"},{"id":1035,"name":"hello.txt","nodeType":"TextFile","path":"tests/test_apps/subdomaintestmodule/static","text":"Hello Subdomain\n"},{"attributeType":"str","col":4,"comment":"null","endLoc":93,"id":1036,"name":"__module__","nodeType":"Attribute","startLoc":93,"text":"__module__"},{"attributeType":"dict","col":4,"comment":"null","endLoc":94,"id":1037,"name":"__annotations__","nodeType":"Attribute","startLoc":94,"text":"__annotations__"},{"col":4,"comment":"null","endLoc":468,"header":"def expect_order(self, order, output)","id":1038,"name":"expect_order","nodeType":"Function","startLoc":464,"text":"def expect_order(self, order, output):\n # skip the header and match the start of each row\n for expect, line in zip(order, output.splitlines()[2:]):\n # do this instead of startswith for nicer pytest output\n assert line[: len(expect)] == expect"},{"col":4,"comment":"Get the template source, filename and reload helper for a template.\n It's passed the environment and template name and has to return a\n tuple in the form ``(source, filename, uptodate)`` or raise a\n `TemplateNotFound` error if it can't locate the template.\n\n The source part of the returned tuple must be the source of the\n template as unicode string or a ASCII bytestring. The filename should\n be the name of the file on the filesystem if it was loaded from there,\n otherwise `None`. The filename is used by python for the tracebacks\n if no loader extension is used.\n\n The last item in the tuple is the `uptodate` function. If auto\n reloading is enabled it's always called to check if the template\n changed. No arguments are passed so the function must store the\n old state somewhere (for example in a closure). If it returns `False`\n the template will be reloaded.\n ","endLoc":93,"header":"def get_source(self, environment, template)","id":1039,"name":"get_source","nodeType":"Function","startLoc":71,"text":"def get_source(self, environment, template):\n \"\"\"Get the template source, filename and reload helper for a template.\n It's passed the environment and template name and has to return a\n tuple in the form ``(source, filename, uptodate)`` or raise a\n `TemplateNotFound` error if it can't locate the template.\n\n The source part of the returned tuple must be the source of the\n template as unicode string or a ASCII bytestring. The filename should\n be the name of the file on the filesystem if it was loaded from there,\n otherwise `None`. The filename is used by python for the tracebacks\n if no loader extension is used.\n\n The last item in the tuple is the `uptodate` function. If auto\n reloading is enabled it's always called to check if the template\n changed. No arguments are passed so the function must store the\n old state somewhere (for example in a closure). If it returns `False`\n the template will be reloaded.\n \"\"\"\n if not self.has_source_access:\n raise RuntimeError(\n \"%s cannot provide access to the source\" % self.__class__.__name__\n )\n raise TemplateNotFound(template)"},{"col":0,"comment":"null","endLoc":44,"header":"def test_teardown_with_previous_exception(app)","id":1040,"name":"test_teardown_with_previous_exception","nodeType":"Function","startLoc":30,"text":"def test_teardown_with_previous_exception(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n\n with app.test_request_context():\n assert buffer == []\n assert buffer == [None]"},{"id":1041,"name":"tests.rst","nodeType":"TextFile","path":"docs/tutorial","text":".. currentmodule:: flask\n\nTest Coverage\n=============\n\nWriting unit tests for your application lets you check that the code\nyou wrote works the way you expect. Flask provides a test client that\nsimulates requests to the application and returns the response data.\n\nYou should test as much of your code as possible. Code in functions only\nruns when the function is called, and code in branches, such as ``if``\nblocks, only runs when the condition is met. You want to make sure that\neach function is tested with data that covers each branch.\n\nThe closer you get to 100% coverage, the more comfortable you can be\nthat making a change won't unexpectedly change other behavior. However,\n100% coverage doesn't guarantee that your application doesn't have bugs.\nIn particular, it doesn't test how the user interacts with the\napplication in the browser. Despite this, test coverage is an important\ntool to use during development.\n\n.. note::\n This is being introduced late in the tutorial, but in your future\n projects you should test as you develop.\n\nYou'll use `pytest`_ and `coverage`_ to test and measure your code.\nInstall them both:\n\n.. code-block:: none\n\n $ pip install pytest coverage\n\n.. _pytest: https://pytest.readthedocs.io/\n.. _coverage: https://coverage.readthedocs.io/\n\n\nSetup and Fixtures\n------------------\n\nThe test code is located in the ``tests`` directory. This directory is\n*next to* the ``flaskr`` package, not inside it. The\n``tests/conftest.py`` file contains setup functions called *fixtures*\nthat each test will use. Tests are in Python modules that start with\n``test_``, and each test function in those modules also starts with\n``test_``.\n\nEach test will create a new temporary database file and populate some\ndata that will be used in the tests. Write a SQL file to insert that\ndata.\n\n.. code-block:: sql\n :caption: ``tests/data.sql``\n\n INSERT INTO user (username, password)\n VALUES\n ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),\n ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');\n\n INSERT INTO post (title, body, author_id, created)\n VALUES\n ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');\n\nThe ``app`` fixture will call the factory and pass ``test_config`` to\nconfigure the application and database for testing instead of using your\nlocal development configuration.\n\n.. code-block:: python\n :caption: ``tests/conftest.py``\n\n import os\n import tempfile\n\n import pytest\n from flaskr import create_app\n from flaskr.db import get_db, init_db\n\n with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:\n _data_sql = f.read().decode('utf8')\n\n\n @pytest.fixture\n def app():\n db_fd, db_path = tempfile.mkstemp()\n\n app = create_app({\n 'TESTING': True,\n 'DATABASE': db_path,\n })\n\n with app.app_context():\n init_db()\n get_db().executescript(_data_sql)\n\n yield app\n\n os.close(db_fd)\n os.unlink(db_path)\n\n\n @pytest.fixture\n def client(app):\n return app.test_client()\n\n\n @pytest.fixture\n def runner(app):\n return app.test_cli_runner()\n\n:func:`tempfile.mkstemp` creates and opens a temporary file, returning\nthe file descriptor and the path to it. The ``DATABASE`` path is\noverridden so it points to this temporary path instead of the instance\nfolder. After setting the path, the database tables are created and the\ntest data is inserted. After the test is over, the temporary file is\nclosed and removed.\n\n:data:`TESTING` tells Flask that the app is in test mode. Flask changes\nsome internal behavior so it's easier to test, and other extensions can\nalso use the flag to make testing them easier.\n\nThe ``client`` fixture calls\n:meth:`app.test_client() ` with the application\nobject created by the ``app`` fixture. Tests will use the client to make\nrequests to the application without running the server.\n\nThe ``runner`` fixture is similar to ``client``.\n:meth:`app.test_cli_runner() ` creates a runner\nthat can call the Click commands registered with the application.\n\nPytest uses fixtures by matching their function names with the names\nof arguments in the test functions. For example, the ``test_hello``\nfunction you'll write next takes a ``client`` argument. Pytest matches\nthat with the ``client`` fixture function, calls it, and passes the\nreturned value to the test function.\n\n\nFactory\n-------\n\nThere's not much to test about the factory itself. Most of the code will\nbe executed for each test already, so if something fails the other tests\nwill notice.\n\nThe only behavior that can change is passing test config. If config is\nnot passed, there should be some default configuration, otherwise the\nconfiguration should be overridden.\n\n.. code-block:: python\n :caption: ``tests/test_factory.py``\n\n from flaskr import create_app\n\n\n def test_config():\n assert not create_app().testing\n assert create_app({'TESTING': True}).testing\n\n\n def test_hello(client):\n response = client.get('/hello')\n assert response.data == b'Hello, World!'\n\nYou added the ``hello`` route as an example when writing the factory at\nthe beginning of the tutorial. It returns \"Hello, World!\", so the test\nchecks that the response data matches.\n\n\nDatabase\n--------\n\nWithin an application context, ``get_db`` should return the same\nconnection each time it's called. After the context, the connection\nshould be closed.\n\n.. code-block:: python\n :caption: ``tests/test_db.py``\n\n import sqlite3\n\n import pytest\n from flaskr.db import get_db\n\n\n def test_get_close_db(app):\n with app.app_context():\n db = get_db()\n assert db is get_db()\n\n with pytest.raises(sqlite3.ProgrammingError) as e:\n db.execute('SELECT 1')\n\n assert 'closed' in str(e.value)\n\nThe ``init-db`` command should call the ``init_db`` function and output\na message.\n\n.. code-block:: python\n :caption: ``tests/test_db.py``\n\n def test_init_db_command(runner, monkeypatch):\n class Recorder(object):\n called = False\n\n def fake_init_db():\n Recorder.called = True\n\n monkeypatch.setattr('flaskr.db.init_db', fake_init_db)\n result = runner.invoke(args=['init-db'])\n assert 'Initialized' in result.output\n assert Recorder.called\n\nThis test uses Pytest's ``monkeypatch`` fixture to replace the\n``init_db`` function with one that records that it's been called. The\n``runner`` fixture you wrote above is used to call the ``init-db``\ncommand by name.\n\n\nAuthentication\n--------------\n\nFor most of the views, a user needs to be logged in. The easiest way to\ndo this in tests is to make a ``POST`` request to the ``login`` view\nwith the client. Rather than writing that out every time, you can write\na class with methods to do that, and use a fixture to pass it the client\nfor each test.\n\n.. code-block:: python\n :caption: ``tests/conftest.py``\n\n class AuthActions(object):\n def __init__(self, client):\n self._client = client\n\n def login(self, username='test', password='test'):\n return self._client.post(\n '/auth/login',\n data={'username': username, 'password': password}\n )\n\n def logout(self):\n return self._client.get('/auth/logout')\n\n\n @pytest.fixture\n def auth(client):\n return AuthActions(client)\n\nWith the ``auth`` fixture, you can call ``auth.login()`` in a test to\nlog in as the ``test`` user, which was inserted as part of the test\ndata in the ``app`` fixture.\n\nThe ``register`` view should render successfully on ``GET``. On ``POST``\nwith valid form data, it should redirect to the login URL and the user's\ndata should be in the database. Invalid data should display error\nmessages.\n\n.. code-block:: python\n :caption: ``tests/test_auth.py``\n\n import pytest\n from flask import g, session\n from flaskr.db import get_db\n\n\n def test_register(client, app):\n assert client.get('/auth/register').status_code == 200\n response = client.post(\n '/auth/register', data={'username': 'a', 'password': 'a'}\n )\n assert response.headers[\"Location\"] == \"/auth/login\"\n\n with app.app_context():\n assert get_db().execute(\n \"SELECT * FROM user WHERE username = 'a'\",\n ).fetchone() is not None\n\n\n @pytest.mark.parametrize(('username', 'password', 'message'), (\n ('', '', b'Username is required.'),\n ('a', '', b'Password is required.'),\n ('test', 'test', b'already registered'),\n ))\n def test_register_validate_input(client, username, password, message):\n response = client.post(\n '/auth/register',\n data={'username': username, 'password': password}\n )\n assert message in response.data\n\n:meth:`client.get() ` makes a ``GET`` request\nand returns the :class:`Response` object returned by Flask. Similarly,\n:meth:`client.post() ` makes a ``POST``\nrequest, converting the ``data`` dict into form data.\n\nTo test that the page renders successfully, a simple request is made and\nchecked for a ``200 OK`` :attr:`~Response.status_code`. If\nrendering failed, Flask would return a ``500 Internal Server Error``\ncode.\n\n:attr:`~Response.headers` will have a ``Location`` header with the login\nURL when the register view redirects to the login view.\n\n:attr:`~Response.data` contains the body of the response as bytes. If\nyou expect a certain value to render on the page, check that it's in\n``data``. Bytes must be compared to bytes. If you want to compare text,\nuse :meth:`get_data(as_text=True) `\ninstead.\n\n``pytest.mark.parametrize`` tells Pytest to run the same test function\nwith different arguments. You use it here to test different invalid\ninput and error messages without writing the same code three times.\n\nThe tests for the ``login`` view are very similar to those for\n``register``. Rather than testing the data in the database,\n:data:`session` should have ``user_id`` set after logging in.\n\n.. code-block:: python\n :caption: ``tests/test_auth.py``\n\n def test_login(client, auth):\n assert client.get('/auth/login').status_code == 200\n response = auth.login()\n assert response.headers[\"Location\"] == \"/\"\n\n with client:\n client.get('/')\n assert session['user_id'] == 1\n assert g.user['username'] == 'test'\n\n\n @pytest.mark.parametrize(('username', 'password', 'message'), (\n ('a', 'test', b'Incorrect username.'),\n ('test', 'a', b'Incorrect password.'),\n ))\n def test_login_validate_input(auth, username, password, message):\n response = auth.login(username, password)\n assert message in response.data\n\nUsing ``client`` in a ``with`` block allows accessing context variables\nsuch as :data:`session` after the response is returned. Normally,\naccessing ``session`` outside of a request would raise an error.\n\nTesting ``logout`` is the opposite of ``login``. :data:`session` should\nnot contain ``user_id`` after logging out.\n\n.. code-block:: python\n :caption: ``tests/test_auth.py``\n\n def test_logout(client, auth):\n auth.login()\n\n with client:\n auth.logout()\n assert 'user_id' not in session\n\n\nBlog\n----\n\nAll the blog views use the ``auth`` fixture you wrote earlier. Call\n``auth.login()`` and subsequent requests from the client will be logged\nin as the ``test`` user.\n\nThe ``index`` view should display information about the post that was\nadded with the test data. When logged in as the author, there should be\na link to edit the post.\n\nYou can also test some more authentication behavior while testing the\n``index`` view. When not logged in, each page shows links to log in or\nregister. When logged in, there's a link to log out.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n import pytest\n from flaskr.db import get_db\n\n\n def test_index(client, auth):\n response = client.get('/')\n assert b\"Log In\" in response.data\n assert b\"Register\" in response.data\n\n auth.login()\n response = client.get('/')\n assert b'Log Out' in response.data\n assert b'test title' in response.data\n assert b'by test on 2018-01-01' in response.data\n assert b'test\\nbody' in response.data\n assert b'href=\"/1/update\"' in response.data\n\nA user must be logged in to access the ``create``, ``update``, and\n``delete`` views. The logged in user must be the author of the post to\naccess ``update`` and ``delete``, otherwise a ``403 Forbidden`` status\nis returned. If a ``post`` with the given ``id`` doesn't exist,\n``update`` and ``delete`` should return ``404 Not Found``.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n @pytest.mark.parametrize('path', (\n '/create',\n '/1/update',\n '/1/delete',\n ))\n def test_login_required(client, path):\n response = client.post(path)\n assert response.headers[\"Location\"] == \"/auth/login\"\n\n\n def test_author_required(app, client, auth):\n # change the post author to another user\n with app.app_context():\n db = get_db()\n db.execute('UPDATE post SET author_id = 2 WHERE id = 1')\n db.commit()\n\n auth.login()\n # current user can't modify other user's post\n assert client.post('/1/update').status_code == 403\n assert client.post('/1/delete').status_code == 403\n # current user doesn't see edit link\n assert b'href=\"/1/update\"' not in client.get('/').data\n\n\n @pytest.mark.parametrize('path', (\n '/2/update',\n '/2/delete',\n ))\n def test_exists_required(client, auth, path):\n auth.login()\n assert client.post(path).status_code == 404\n\nThe ``create`` and ``update`` views should render and return a\n``200 OK`` status for a ``GET`` request. When valid data is sent in a\n``POST`` request, ``create`` should insert the new post data into the\ndatabase, and ``update`` should modify the existing data. Both pages\nshould show an error message on invalid data.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n def test_create(client, auth, app):\n auth.login()\n assert client.get('/create').status_code == 200\n client.post('/create', data={'title': 'created', 'body': ''})\n\n with app.app_context():\n db = get_db()\n count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]\n assert count == 2\n\n\n def test_update(client, auth, app):\n auth.login()\n assert client.get('/1/update').status_code == 200\n client.post('/1/update', data={'title': 'updated', 'body': ''})\n\n with app.app_context():\n db = get_db()\n post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()\n assert post['title'] == 'updated'\n\n\n @pytest.mark.parametrize('path', (\n '/create',\n '/1/update',\n ))\n def test_create_update_validate(client, auth, path):\n auth.login()\n response = client.post(path, data={'title': '', 'body': ''})\n assert b'Title is required.' in response.data\n\nThe ``delete`` view should redirect to the index URL and the post should\nno longer exist in the database.\n\n.. code-block:: python\n :caption: ``tests/test_blog.py``\n\n def test_delete(client, auth, app):\n auth.login()\n response = client.post('/1/delete')\n assert response.headers[\"Location\"] == \"/\"\n\n with app.app_context():\n db = get_db()\n post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()\n assert post is None\n\n\nRunning the Tests\n-----------------\n\nSome extra configuration, which is not required but makes running tests with coverage\nless verbose, can be added to the project's ``pyproject.toml`` file.\n\n.. code-block:: toml\n :caption: ``pyproject.toml``\n\n [tool.pytest.ini_options]\n testpaths = [\"tests\"]\n\n [tool.coverage.run]\n branch = true\n source = [\"flaskr\"]\n\nTo run the tests, use the ``pytest`` command. It will find and run all\nthe test functions you've written.\n\n.. code-block:: none\n\n $ pytest\n\n ========================= test session starts ==========================\n platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0\n rootdir: /home/user/Projects/flask-tutorial\n collected 23 items\n\n tests/test_auth.py ........ [ 34%]\n tests/test_blog.py ............ [ 86%]\n tests/test_db.py .. [ 95%]\n tests/test_factory.py .. [100%]\n\n ====================== 24 passed in 0.64 seconds =======================\n\nIf any tests fail, pytest will show the error that was raised. You can\nrun ``pytest -v`` to get a list of each test function rather than dots.\n\nTo measure the code coverage of your tests, use the ``coverage`` command\nto run pytest instead of running it directly.\n\n.. code-block:: none\n\n $ coverage run -m pytest\n\nYou can either view a simple coverage report in the terminal:\n\n.. code-block:: none\n\n $ coverage report\n\n Name Stmts Miss Branch BrPart Cover\n ------------------------------------------------------\n flaskr/__init__.py 21 0 2 0 100%\n flaskr/auth.py 54 0 22 0 100%\n flaskr/blog.py 54 0 16 0 100%\n flaskr/db.py 24 0 4 0 100%\n ------------------------------------------------------\n TOTAL 153 0 44 0 100%\n\nAn HTML report allows you to see which lines were covered in each file:\n\n.. code-block:: none\n\n $ coverage html\n\nThis generates files in the ``htmlcov`` directory. Open\n``htmlcov/index.html`` in your browser to see the report.\n\nContinue to :doc:`deploy`.\n"},{"id":1042,"name":"tox.ini","nodeType":"TextFile","path":"","text":"[tox]\nenvlist =\n py3{12,11,10,9,8,7}\n pypy3{9,8,7}\n py311-min\n py37-dev\n style\n typing\n docs\nskip_missing_interpreters = true\n\n[testenv]\npackage = wheel\nwheel_build_env = .pkg\nenvtmpdir = {toxworkdir}/tmp/{envname}\ndeps =\n -r requirements/tests.txt\n min: -r requirements/tests-pallets-min.txt\n dev: https://github.com/pallets/werkzeug/archive/refs/heads/main.tar.gz\n dev: https://github.com/pallets/jinja/archive/refs/heads/main.tar.gz\n dev: https://github.com/pallets/markupsafe/archive/refs/heads/main.tar.gz\n dev: https://github.com/pallets/itsdangerous/archive/refs/heads/main.tar.gz\n dev: https://github.com/pallets/click/archive/refs/heads/main.tar.gz\n# examples/tutorial[test]\n# examples/javascript[test]\n# commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs:tests examples}\ncommands = pytest -v --tb=short --basetemp={envtmpdir} {posargs:tests}\n\n[testenv:style]\ndeps = pre-commit\nskip_install = true\ncommands = pre-commit run --all-files\n\n[testenv:typing]\npackage = wheel\nwheel_build_env = .pkg\ndeps = -r requirements/typing.txt\ncommands = mypy\n\n[testenv:docs]\npackage = wheel\nwheel_build_env = .pkg\ndeps = -r requirements/docs.txt\ncommands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html\n"},{"col":4,"comment":"Create a tagger for the given serializer.","endLoc":68,"header":"def __init__(self, serializer: \"TaggedJSONSerializer\") -> None","id":1043,"name":"__init__","nodeType":"Function","startLoc":66,"text":"def __init__(self, serializer: \"TaggedJSONSerializer\") -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer"},{"col":0,"comment":"null","endLoc":152,"header":"def test_implicit_head(app, client)","id":1044,"name":"test_implicit_head","nodeType":"Function","startLoc":141,"text":"def test_implicit_head(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return flask.Response(\"Blub\", headers={\"X-Method\": flask.request.method})\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.data == b\"Blub\"\n assert rv.headers[\"X-Method\"] == \"GET\"\n rv = client.head(\"/\")\n assert rv.data == b\"\"\n assert rv.headers[\"X-Method\"] == \"HEAD\""},{"id":1045,"name":"examples/tutorial/flaskr/templates/blog","nodeType":"Package"},{"id":1046,"name":"update.html","nodeType":"TextFile","path":"examples/tutorial/flaskr/templates/blog","text":"{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}Edit \"{{ post['title'] }}\"{% endblock %}

\n{% endblock %}\n\n{% block content %}\n
\n \n \n \n \n \n
\n
\n
\n \n
\n{% endblock %}\n"},{"col":0,"comment":"null","endLoc":168,"header":"def test_explicit_head(app, client)","id":1047,"name":"test_explicit_head","nodeType":"Function","startLoc":155,"text":"def test_explicit_head(app, client):\n class Index(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n def head(self):\n return flask.Response(\"\", headers={\"X-Method\": \"HEAD\"})\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n rv = client.get(\"/\")\n assert rv.data == b\"GET\"\n rv = client.head(\"/\")\n assert rv.data == b\"\"\n assert rv.headers[\"X-Method\"] == \"HEAD\""},{"col":0,"comment":"null","endLoc":186,"header":"def test_endpoint_override(app)","id":1048,"name":"test_endpoint_override","nodeType":"Function","startLoc":171,"text":"def test_endpoint_override(app):\n app.debug = True\n\n class Index(flask.views.View):\n methods = [\"GET\", \"POST\"]\n\n def dispatch_request(self):\n return flask.request.method\n\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n with pytest.raises(AssertionError):\n app.add_url_rule(\"/\", view_func=Index.as_view(\"index\"))\n\n # But these tests should still pass. We just log a warning.\n common_test(app)"},{"col":0,"comment":"Set up ``os.environ`` at the start of the test session to have\n standard values. Returns a list of operations that is used by\n :func:`._reset_os_environ` after each test.\n ","endLoc":35,"header":"@pytest.fixture(scope=\"session\", autouse=True)\ndef _standard_os_environ()","id":1049,"name":"_standard_os_environ","nodeType":"Function","startLoc":13,"text":"@pytest.fixture(scope=\"session\", autouse=True)\ndef _standard_os_environ():\n \"\"\"Set up ``os.environ`` at the start of the test session to have\n standard values. Returns a list of operations that is used by\n :func:`._reset_os_environ` after each test.\n \"\"\"\n mp = monkeypatch.MonkeyPatch()\n out = (\n (os.environ, \"FLASK_ENV_FILE\", monkeypatch.notset),\n (os.environ, \"FLASK_APP\", monkeypatch.notset),\n (os.environ, \"FLASK_DEBUG\", monkeypatch.notset),\n (os.environ, \"FLASK_RUN_FROM_CLI\", monkeypatch.notset),\n (os.environ, \"WERKZEUG_RUN_MAIN\", monkeypatch.notset),\n )\n\n for _, key, value in out:\n if value is monkeypatch.notset:\n mp.delenv(key, False)\n else:\n mp.setenv(key, value)\n\n yield out\n mp.undo()"},{"id":1050,"name":"caching.rst","nodeType":"TextFile","path":"docs/patterns","text":"Caching\n=======\n\nWhen your application runs slow, throw some caches in. Well, at least\nit's the easiest way to speed up things. What does a cache do? Say you\nhave a function that takes some time to complete but the results would\nstill be good enough if they were 5 minutes old. So then the idea is that\nyou actually put the result of that calculation into a cache for some\ntime.\n\nFlask itself does not provide caching for you, but `Flask-Caching`_, an\nextension for Flask does. Flask-Caching supports various backends, and it is\neven possible to develop your own caching backend.\n\n\n.. _Flask-Caching: https://flask-caching.readthedocs.io/en/latest/\n"},{"className":"Exception","col":0,"comment":"null","endLoc":1947,"id":1051,"nodeType":"Class","startLoc":1947,"text":"class Exception(BaseException): ..."},{"className":"BaseException","col":0,"comment":"null","endLoc":1939,"id":1052,"nodeType":"Class","startLoc":1927,"text":"class BaseException:\n args: tuple[Any, ...]\n __cause__: BaseException | None\n __context__: BaseException | None\n __suppress_context__: bool\n __traceback__: TracebackType | None\n def __init__(self, *args: object) -> None: ...\n def __setstate__(self, __state: dict[str, Any] | None) -> None: ...\n def with_traceback(self, __tb: TracebackType | None) -> Self: ...\n if sys.version_info >= (3, 11):\n # only present after add_note() is called\n __notes__: list[str]\n def add_note(self, __note: str) -> None: ..."},{"col":4,"comment":"null","endLoc":1934,"header":"def __setstate__(self, __state: dict[str, Any] | None) -> None","id":1053,"name":"__setstate__","nodeType":"Function","startLoc":1934,"text":"def __setstate__(self, __state: dict[str, Any] | None) -> None: ..."},{"col":4,"comment":"null","endLoc":1935,"header":"def with_traceback(self, __tb: TracebackType | None) -> Self","id":1054,"name":"with_traceback","nodeType":"Function","startLoc":1935,"text":"def with_traceback(self, __tb: TracebackType | None) -> Self: ..."},{"col":8,"comment":"null","endLoc":1939,"header":"def add_note(self, __note: str) -> None","id":1055,"name":"add_note","nodeType":"Function","startLoc":1939,"text":"def add_note(self, __note: str) -> None: ..."},{"attributeType":"(Any, ...)","col":4,"comment":"null","endLoc":1928,"id":1056,"name":"args","nodeType":"Attribute","startLoc":1928,"text":"args"},{"className":"RenderTemplateView","col":0,"comment":"null","endLoc":108,"id":1057,"nodeType":"Class","startLoc":103,"text":"class RenderTemplateView(View):\n def __init__(self: RenderTemplateView, template_name: str) -> None:\n self.template_name = template_name\n\n def dispatch_request(self: RenderTemplateView) -> str:\n return render_template(self.template_name)"},{"col":4,"comment":"null","endLoc":105,"header":"def __init__(self: RenderTemplateView, template_name: str) -> None","id":1058,"name":"__init__","nodeType":"Function","startLoc":104,"text":"def __init__(self: RenderTemplateView, template_name: str) -> None:\n self.template_name = template_name"},{"col":4,"comment":"null","endLoc":108,"header":"def dispatch_request(self: RenderTemplateView) -> str","id":1059,"name":"dispatch_request","nodeType":"Function","startLoc":107,"text":"def dispatch_request(self: RenderTemplateView) -> str:\n return render_template(self.template_name)"},{"className":"TestStreaming","col":0,"comment":"null","endLoc":300,"id":1060,"nodeType":"Class","startLoc":229,"text":"class TestStreaming:\n def test_streaming_with_context(self, app, client):\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(generate()))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n\n def test_streaming_with_context_as_decorator(self, app, client):\n @app.route(\"/\")\n def index():\n @flask.stream_with_context\n def generate(hello):\n yield hello\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(generate(\"Hello \"))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n\n def test_streaming_with_context_and_custom_close(self, app, client):\n called = []\n\n class Wrapper:\n def __init__(self, gen):\n self._gen = gen\n\n def __iter__(self):\n return self\n\n def close(self):\n called.append(42)\n\n def __next__(self):\n return next(self._gen)\n\n next = __next__\n\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(Wrapper(generate())))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n assert called == [42]\n\n def test_stream_keeps_session(self, app, client):\n @app.route(\"/\")\n def index():\n flask.session[\"test\"] = \"flask\"\n\n @flask.stream_with_context\n def gen():\n yield flask.session[\"test\"]\n\n return flask.Response(gen())\n\n rv = client.get(\"/\")\n assert rv.data == b\"flask\""},{"attributeType":"str","col":8,"comment":"null","endLoc":105,"id":1061,"name":"template_name","nodeType":"Attribute","startLoc":105,"text":"self.template_name"},{"col":4,"comment":"null","endLoc":241,"header":"def test_streaming_with_context(self, app, client)","id":1062,"name":"test_streaming_with_context","nodeType":"Function","startLoc":230,"text":"def test_streaming_with_context(self, app, client):\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(generate()))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\""},{"col":0,"comment":"Get whether debug mode should be enabled for the app, indicated by the\n :envvar:`FLASK_DEBUG` environment variable. The default is ``False``.\n ","endLoc":34,"header":"def get_debug_flag() -> bool","id":1063,"name":"get_debug_flag","nodeType":"Function","startLoc":29,"text":"def get_debug_flag() -> bool:\n \"\"\"Get whether debug mode should be enabled for the app, indicated by the\n :envvar:`FLASK_DEBUG` environment variable. The default is ``False``.\n \"\"\"\n val = os.environ.get(\"FLASK_DEBUG\")\n return bool(val and val.lower() not in {\"0\", \"false\", \"no\"})"},{"col":0,"comment":"null","endLoc":204,"header":"def test_methods_var_inheritance(app, client)","id":1064,"name":"test_methods_var_inheritance","nodeType":"Function","startLoc":189,"text":"def test_methods_var_inheritance(app, client):\n class BaseView(flask.views.MethodView):\n methods = [\"GET\", \"PROPFIND\"]\n\n class ChildView(BaseView):\n def get(self):\n return \"GET\"\n\n def propfind(self):\n return \"PROPFIND\"\n\n app.add_url_rule(\"/\", view_func=ChildView.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.open(\"/\", method=\"PROPFIND\").data == b\"PROPFIND\"\n assert ChildView.methods == {\"PROPFIND\", \"GET\"}"},{"col":0,"comment":"null","endLoc":20,"header":"@app.route(\"/str\")\ndef hello_str() -> str","id":1066,"name":"hello_str","nodeType":"Function","startLoc":18,"text":"@app.route(\"/str\")\ndef hello_str() -> str:\n return \"

Hello, World!

\""},{"col":0,"comment":"null","endLoc":25,"header":"@app.route(\"/bytes\")\ndef hello_bytes() -> bytes","id":1067,"name":"hello_bytes","nodeType":"Function","startLoc":23,"text":"@app.route(\"/bytes\")\ndef hello_bytes() -> bytes:\n return b\"

Hello, World!

\""},{"col":0,"comment":"null","endLoc":30,"header":"@app.route(\"/json\")\ndef hello_json() -> Response","id":1068,"name":"hello_json","nodeType":"Function","startLoc":28,"text":"@app.route(\"/json\")\ndef hello_json() -> Response:\n return jsonify(\"Hello, World!\")"},{"col":4,"comment":"null","endLoc":255,"header":"def test_streaming_with_context_as_decorator(self, app, client)","id":1069,"name":"test_streaming_with_context_as_decorator","nodeType":"Function","startLoc":243,"text":"def test_streaming_with_context_as_decorator(self, app, client):\n @app.route(\"/\")\n def index():\n @flask.stream_with_context\n def generate(hello):\n yield hello\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(generate(\"Hello \"))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\""},{"col":0,"comment":"null","endLoc":35,"header":"@app.route(\"/json/dict\")\ndef hello_json_dict() -> t.Dict[str, t.Any]","id":1070,"name":"hello_json_dict","nodeType":"Function","startLoc":33,"text":"@app.route(\"/json/dict\")\ndef hello_json_dict() -> t.Dict[str, t.Any]:\n return {\"response\": \"Hello, World!\"}"},{"col":0,"comment":"null","endLoc":40,"header":"@app.route(\"/json/dict\")\ndef hello_json_list() -> t.List[t.Any]","id":1071,"name":"hello_json_list","nodeType":"Function","startLoc":38,"text":"@app.route(\"/json/dict\")\ndef hello_json_list() -> t.List[t.Any]:\n return [{\"message\": \"Hello\"}, {\"message\": \"World\"}]"},{"col":0,"comment":"null","endLoc":49,"header":"@app.route(\"/typed-dict\")\ndef typed_dict() -> StatusJSON","id":1072,"name":"typed_dict","nodeType":"Function","startLoc":47,"text":"@app.route(\"/typed-dict\")\ndef typed_dict() -> StatusJSON:\n return {\"status\": \"ok\"}"},{"col":0,"comment":"null","endLoc":58,"header":"@app.route(\"/generator\")\ndef hello_generator() -> t.Generator[str, None, None]","id":1073,"name":"hello_generator","nodeType":"Function","startLoc":52,"text":"@app.route(\"/generator\")\ndef hello_generator() -> t.Generator[str, None, None]:\n def show() -> t.Generator[str, None, None]:\n for x in range(100):\n yield f\"data:{x}\\n\\n\"\n\n return show()"},{"col":0,"comment":"null","endLoc":60,"header":"def test_teardown_with_handled_exception(app)","id":1074,"name":"test_teardown_with_handled_exception","nodeType":"Function","startLoc":47,"text":"def test_teardown_with_handled_exception(app):\n buffer = []\n\n @app.teardown_request\n def end_of_request(exception):\n buffer.append(exception)\n\n with app.test_request_context():\n assert buffer == []\n try:\n raise Exception(\"dummy\")\n except Exception:\n pass\n assert buffer == [None]"},{"col":0,"comment":"null","endLoc":223,"header":"def test_multiple_inheritance(app, client)","id":1075,"name":"test_multiple_inheritance","nodeType":"Function","startLoc":207,"text":"def test_multiple_inheritance(app, client):\n class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n class DeleteView(flask.views.MethodView):\n def delete(self):\n return \"DELETE\"\n\n class GetDeleteView(GetView, DeleteView):\n pass\n\n app.add_url_rule(\"/\", view_func=GetDeleteView.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.delete(\"/\").data == b\"DELETE\"\n assert sorted(GetDeleteView.methods) == [\"DELETE\", \"GET\"]"},{"col":0,"comment":"Reset ``os.environ`` to the standard environ after each test,\n in case a test changed something without cleaning up.\n ","endLoc":43,"header":"@pytest.fixture(autouse=True)\ndef _reset_os_environ(monkeypatch, _standard_os_environ)","id":1076,"name":"_reset_os_environ","nodeType":"Function","startLoc":38,"text":"@pytest.fixture(autouse=True)\ndef _reset_os_environ(monkeypatch, _standard_os_environ):\n \"\"\"Reset ``os.environ`` to the standard environ after each test,\n in case a test changed something without cleaning up.\n \"\"\"\n monkeypatch._setitem.extend(_standard_os_environ)"},{"fileName":"tag.py","filePath":"src/flask/json","id":1078,"nodeType":"File","text":"\"\"\"\nTagged JSON\n~~~~~~~~~~~\n\nA compact representation for lossless serialization of non-standard JSON\ntypes. :class:`~flask.sessions.SecureCookieSessionInterface` uses this\nto serialize the session data, but it may be useful in other places. It\ncan be extended to support other types.\n\n.. autoclass:: TaggedJSONSerializer\n :members:\n\n.. autoclass:: JSONTag\n :members:\n\nLet's see an example that adds support for\n:class:`~collections.OrderedDict`. Dicts don't have an order in JSON, so\nto handle this we will dump the items as a list of ``[key, value]``\npairs. Subclass :class:`JSONTag` and give it the new key ``' od'`` to\nidentify the type. The session serializer processes dicts first, so\ninsert the new tag at the front of the order since ``OrderedDict`` must\nbe processed before ``dict``.\n\n.. code-block:: python\n\n from flask.json.tag import JSONTag\n\n class TagOrderedDict(JSONTag):\n __slots__ = ('serializer',)\n key = ' od'\n\n def check(self, value):\n return isinstance(value, OrderedDict)\n\n def to_json(self, value):\n return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]\n\n def to_python(self, value):\n return OrderedDict(value)\n\n app.session_interface.serializer.register(TagOrderedDict, index=0)\n\"\"\"\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\n\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\n\nfrom ..json import dumps\nfrom ..json import loads\n\n\nclass JSONTag:\n \"\"\"Base class for defining type tags for :class:`TaggedJSONSerializer`.\"\"\"\n\n __slots__ = (\"serializer\",)\n\n #: The tag to mark the serialized object with. If ``None``, this tag is\n #: only used as an intermediate step during tagging.\n key: t.Optional[str] = None\n\n def __init__(self, serializer: \"TaggedJSONSerializer\") -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer\n\n def check(self, value: t.Any) -> bool:\n \"\"\"Check if the given value should be tagged by this tag.\"\"\"\n raise NotImplementedError\n\n def to_json(self, value: t.Any) -> t.Any:\n \"\"\"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.\"\"\"\n raise NotImplementedError\n\n def to_python(self, value: t.Any) -> t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError\n\n def tag(self, value: t.Any) -> t.Any:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}\n\n\nclass TagDict(JSONTag):\n \"\"\"Tag for 1-item dicts whose only key matches a registered tag.\n\n Internally, the dict key is suffixed with `__`, and the suffix is removed\n when deserializing.\n \"\"\"\n\n __slots__ = ()\n key = \" di\"\n\n def check(self, value: t.Any) -> bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )\n\n def to_json(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}\n\n def to_python(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}\n\n\nclass PassDict(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, dict)\n\n def to_json(self, value: t.Any) -> t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}\n\n tag = to_json\n\n\nclass TagTuple(JSONTag):\n __slots__ = ()\n key = \" t\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, tuple)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n def to_python(self, value: t.Any) -> t.Any:\n return tuple(value)\n\n\nclass PassList(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, list)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n tag = to_json\n\n\nclass TagBytes(JSONTag):\n __slots__ = ()\n key = \" b\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, bytes)\n\n def to_json(self, value: t.Any) -> t.Any:\n return b64encode(value).decode(\"ascii\")\n\n def to_python(self, value: t.Any) -> t.Any:\n return b64decode(value)\n\n\nclass TagMarkup(JSONTag):\n \"\"\"Serialize anything matching the :class:`~markupsafe.Markup` API by\n having a ``__html__`` method to the result of that method. Always\n deserializes to an instance of :class:`~markupsafe.Markup`.\"\"\"\n\n __slots__ = ()\n key = \" m\"\n\n def check(self, value: t.Any) -> bool:\n return callable(getattr(value, \"__html__\", None))\n\n def to_json(self, value: t.Any) -> t.Any:\n return str(value.__html__())\n\n def to_python(self, value: t.Any) -> t.Any:\n return Markup(value)\n\n\nclass TagUUID(JSONTag):\n __slots__ = ()\n key = \" u\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, UUID)\n\n def to_json(self, value: t.Any) -> t.Any:\n return value.hex\n\n def to_python(self, value: t.Any) -> t.Any:\n return UUID(value)\n\n\nclass TagDateTime(JSONTag):\n __slots__ = ()\n key = \" d\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, datetime)\n\n def to_json(self, value: t.Any) -> t.Any:\n return http_date(value)\n\n def to_python(self, value: t.Any) -> t.Any:\n return parse_date(value)\n\n\nclass TaggedJSONSerializer:\n \"\"\"Serializer that uses a tag system to compactly represent objects that\n are not JSON types. Passed as the intermediate serializer to\n :class:`itsdangerous.Serializer`.\n\n The following extra types are supported:\n\n * :class:`dict`\n * :class:`tuple`\n * :class:`bytes`\n * :class:`~markupsafe.Markup`\n * :class:`~uuid.UUID`\n * :class:`~datetime.datetime`\n \"\"\"\n\n __slots__ = (\"tags\", \"order\")\n\n #: Tag classes to bind when creating the serializer. Other tags can be\n #: added later using :meth:`~register`.\n default_tags = [\n TagDict,\n PassDict,\n TagTuple,\n PassList,\n TagBytes,\n TagMarkup,\n TagUUID,\n TagDateTime,\n ]\n\n def __init__(self) -> None:\n self.tags: t.Dict[str, JSONTag] = {}\n self.order: t.List[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)\n\n def register(\n self,\n tag_class: t.Type[JSONTag],\n force: bool = False,\n index: t.Optional[int] = None,\n ) -> None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n \"\"\"\n tag = tag_class(self)\n key = tag.key\n\n if key is not None:\n if not force and key in self.tags:\n raise KeyError(f\"Tag '{key}' is already registered.\")\n\n self.tags[key] = tag\n\n if index is None:\n self.order.append(tag)\n else:\n self.order.insert(index, tag)\n\n def tag(self, value: t.Any) -> t.Dict[str, t.Any]:\n \"\"\"Convert a value to a tagged representation if necessary.\"\"\"\n for tag in self.order:\n if tag.check(value):\n return tag.tag(value)\n\n return value\n\n def untag(self, value: t.Dict[str, t.Any]) -> t.Any:\n \"\"\"Convert a tagged representation back to the original type.\"\"\"\n if len(value) != 1:\n return value\n\n key = next(iter(value))\n\n if key not in self.tags:\n return value\n\n return self.tags[key].to_python(value[key])\n\n def dumps(self, value: t.Any) -> str:\n \"\"\"Tag the value and dump it to a compact JSON string.\"\"\"\n return dumps(self.tag(value), separators=(\",\", \":\"))\n\n def loads(self, value: str) -> t.Any:\n \"\"\"Load data from a JSON string and deserialized any tagged objects.\"\"\"\n return loads(value, object_hook=self.untag)\n"},{"col":4,"comment":"null","endLoc":286,"header":"def test_streaming_with_context_and_custom_close(self, app, client)","id":1079,"name":"test_streaming_with_context_and_custom_close","nodeType":"Function","startLoc":257,"text":"def test_streaming_with_context_and_custom_close(self, app, client):\n called = []\n\n class Wrapper:\n def __init__(self, gen):\n self._gen = gen\n\n def __iter__(self):\n return self\n\n def close(self):\n called.append(42)\n\n def __next__(self):\n return next(self._gen)\n\n next = __next__\n\n @app.route(\"/\")\n def index():\n def generate():\n yield \"Hello \"\n yield flask.request.args[\"name\"]\n yield \"!\"\n\n return flask.Response(flask.stream_with_context(Wrapper(generate())))\n\n rv = client.get(\"/?name=World\")\n assert rv.data == b\"Hello World!\"\n assert called == [42]"},{"className":"JSONProvider","col":0,"comment":"A standard set of JSON operations for an application. Subclasses\n of this can be used to customize JSON behavior or use different\n JSON libraries.\n\n To implement a provider for a specific library, subclass this base\n class and implement at least :meth:`dumps` and :meth:`loads`. All\n other methods have default implementations.\n\n To use a different provider, either subclass ``Flask`` and set\n :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n :attr:`app.json ` to an instance of the class.\n\n :param app: An application instance. This will be stored as a\n :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n .. versionadded:: 2.2\n ","endLoc":104,"id":1080,"nodeType":"Class","startLoc":18,"text":"class JSONProvider:\n \"\"\"A standard set of JSON operations for an application. Subclasses\n of this can be used to customize JSON behavior or use different\n JSON libraries.\n\n To implement a provider for a specific library, subclass this base\n class and implement at least :meth:`dumps` and :meth:`loads`. All\n other methods have default implementations.\n\n To use a different provider, either subclass ``Flask`` and set\n :attr:`~flask.Flask.json_provider_class` to a provider class, or set\n :attr:`app.json ` to an instance of the class.\n\n :param app: An application instance. This will be stored as a\n :class:`weakref.proxy` on the :attr:`_app` attribute.\n\n .. versionadded:: 2.2\n \"\"\"\n\n def __init__(self, app: Flask) -> None:\n self._app = weakref.proxy(app)\n\n def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n :param obj: The data to serialize.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError\n\n def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write to a file.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n fp.write(self.dumps(obj, **kwargs))\n\n def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError\n\n def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON read from a file.\n\n :param fp: A file opened for reading text or UTF-8 bytes.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n return self.loads(fp.read(), **kwargs)\n\n def _prepare_response_obj(\n self, args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]\n ) -> t.Any:\n if args and kwargs:\n raise TypeError(\"app.json.response() takes either args or kwargs, not both\")\n\n if not args and not kwargs:\n return None\n\n if len(args) == 1:\n return args[0]\n\n return args or kwargs\n\n def response(self, *args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with the ``application/json``\n mimetype.\n\n The :func:`~flask.json.jsonify` function calls this method for\n the current application.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n \"\"\"\n obj = self._prepare_response_obj(args, kwargs)\n return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")"},{"col":4,"comment":"null","endLoc":38,"header":"def __init__(self, app: Flask) -> None","id":1081,"name":"__init__","nodeType":"Function","startLoc":37,"text":"def __init__(self, app: Flask) -> None:\n self._app = weakref.proxy(app)"},{"col":4,"comment":"null","endLoc":1067,"header":"@overload\n def __init__(self) -> None","id":1082,"name":"__init__","nodeType":"Function","startLoc":1066,"text":"@overload\n def __init__(self) -> None: ..."},{"col":4,"comment":"null","endLoc":1069,"header":"@overload\n def __init__(self: dict[str, _VT], **kwargs: _VT) -> None","id":1083,"name":"__init__","nodeType":"Function","startLoc":1068,"text":"@overload\n def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1071,"header":"@overload\n def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None","id":1084,"name":"__init__","nodeType":"Function","startLoc":1070,"text":"@overload\n def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ..."},{"col":4,"comment":"null","endLoc":1073,"header":"@overload\n def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None","id":1085,"name":"__init__","nodeType":"Function","startLoc":1072,"text":"@overload\n def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1075,"header":"@overload\n def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None","id":1086,"name":"__init__","nodeType":"Function","startLoc":1074,"text":"@overload\n def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ..."},{"col":4,"comment":"null","endLoc":1077,"header":"@overload\n def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None","id":1087,"name":"__init__","nodeType":"Function","startLoc":1076,"text":"@overload\n def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ..."},{"col":4,"comment":"null","endLoc":1081,"header":"@overload\n def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None","id":1088,"name":"__init__","nodeType":"Function","startLoc":1080,"text":"@overload\n def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ..."},{"col":4,"comment":"null","endLoc":1083,"header":"@overload\n def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None","id":1089,"name":"__init__","nodeType":"Function","startLoc":1082,"text":"@overload\n def __init__(self: dict[bytes, bytes], __iterable: Iterable[list[bytes]]) -> None: ..."},{"id":1090,"name":"api.rst","nodeType":"TextFile","path":"docs","text":"API\n===\n\n.. module:: flask\n\nThis part of the documentation covers all the interfaces of Flask. For\nparts where Flask depends on external libraries, we document the most\nimportant right here and provide links to the canonical documentation.\n\n\nApplication Object\n------------------\n\n.. autoclass:: Flask\n :members:\n :inherited-members:\n\n\nBlueprint Objects\n-----------------\n\n.. autoclass:: Blueprint\n :members:\n :inherited-members:\n\nIncoming Request Data\n---------------------\n\n.. autoclass:: Request\n :members:\n :inherited-members:\n :exclude-members: json_module\n\n.. attribute:: request\n\n To access incoming request data, you can use the global `request`\n object. Flask parses incoming request data for you and gives you\n access to it through that global object. Internally Flask makes\n sure that you always get the correct data for the active thread if you\n are in a multithreaded environment.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n The request object is an instance of a :class:`~flask.Request`.\n\n\nResponse Objects\n----------------\n\n.. autoclass:: flask.Response\n :members:\n :inherited-members:\n :exclude-members: json_module\n\nSessions\n--------\n\nIf you have set :attr:`Flask.secret_key` (or configured it from\n:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes\nit possible to remember information from one request to another. The way Flask\ndoes this is by using a signed cookie. The user can look at the session\ncontents, but can't modify it unless they know the secret key, so make sure to\nset that to something complex and unguessable.\n\nTo access the current session you can use the :class:`session` object:\n\n.. class:: session\n\n The session object works pretty much like an ordinary dict, with the\n difference that it keeps track of modifications.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n The following attributes are interesting:\n\n .. attribute:: new\n\n ``True`` if the session is new, ``False`` otherwise.\n\n .. attribute:: modified\n\n ``True`` if the session object detected a modification. Be advised\n that modifications on mutable structures are not picked up\n automatically, in that situation you have to explicitly set the\n attribute to ``True`` yourself. Here an example::\n\n # this change is not picked up because a mutable object (here\n # a list) is changed.\n session['objects'].append(42)\n # so mark it as modified yourself\n session.modified = True\n\n .. attribute:: permanent\n\n If set to ``True`` the session lives for\n :attr:`~flask.Flask.permanent_session_lifetime` seconds. The\n default is 31 days. If set to ``False`` (which is the default) the\n session will be deleted when the user closes the browser.\n\n\nSession Interface\n-----------------\n\n.. versionadded:: 0.8\n\nThe session interface provides a simple way to replace the session\nimplementation that Flask is using.\n\n.. currentmodule:: flask.sessions\n\n.. autoclass:: SessionInterface\n :members:\n\n.. autoclass:: SecureCookieSessionInterface\n :members:\n\n.. autoclass:: SecureCookieSession\n :members:\n\n.. autoclass:: NullSession\n :members:\n\n.. autoclass:: SessionMixin\n :members:\n\n.. admonition:: Notice\n\n The :data:`PERMANENT_SESSION_LIFETIME` config can be an integer or ``timedelta``.\n The :attr:`~flask.Flask.permanent_session_lifetime` attribute is always a\n ``timedelta``.\n\n\nTest Client\n-----------\n\n.. currentmodule:: flask.testing\n\n.. autoclass:: FlaskClient\n :members:\n\n\nTest CLI Runner\n---------------\n\n.. currentmodule:: flask.testing\n\n.. autoclass:: FlaskCliRunner\n :members:\n\n\nApplication Globals\n-------------------\n\n.. currentmodule:: flask\n\nTo share data that is valid for one request only from one function to\nanother, a global variable is not good enough because it would break in\nthreaded environments. Flask provides you with a special object that\nensures it is only valid for the active request and that will return\ndifferent values for each request. In a nutshell: it does the right\nthing, like it does for :class:`request` and :class:`session`.\n\n.. data:: g\n\n A namespace object that can store data during an\n :doc:`application context
`. This is an instance of\n :attr:`Flask.app_ctx_globals_class`, which defaults to\n :class:`ctx._AppCtxGlobals`.\n\n This is a good place to store resources during a request. For\n example, a ``before_request`` function could load a user object from\n a session id, then set ``g.user`` to be used in the view function.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n .. versionchanged:: 0.10\n Bound to the application context instead of the request context.\n\n.. autoclass:: flask.ctx._AppCtxGlobals\n :members:\n\n\nUseful Functions and Classes\n----------------------------\n\n.. data:: current_app\n\n A proxy to the application handling the current request. This is\n useful to access the application without needing to import it, or if\n it can't be imported, such as when using the application factory\n pattern or in blueprints and extensions.\n\n This is only available when an\n :doc:`application context ` is pushed. This happens\n automatically during requests and CLI commands. It can be controlled\n manually with :meth:`~flask.Flask.app_context`.\n\n This is a proxy. See :ref:`notes-on-proxies` for more information.\n\n.. autofunction:: has_request_context\n\n.. autofunction:: copy_current_request_context\n\n.. autofunction:: has_app_context\n\n.. autofunction:: url_for\n\n.. autofunction:: abort\n\n.. autofunction:: redirect\n\n.. autofunction:: make_response\n\n.. autofunction:: after_this_request\n\n.. autofunction:: send_file\n\n.. autofunction:: send_from_directory\n\n\nMessage Flashing\n----------------\n\n.. autofunction:: flash\n\n.. autofunction:: get_flashed_messages\n\n\nJSON Support\n------------\n\n.. module:: flask.json\n\nFlask uses Python's built-in :mod:`json` module for handling JSON by\ndefault. The JSON implementation can be changed by assigning a different\nprovider to :attr:`flask.Flask.json_provider_class` or\n:attr:`flask.Flask.json`. The functions provided by ``flask.json`` will\nuse methods on ``app.json`` if an app context is active.\n\nJinja's ``|tojson`` filter is configured to use the app's JSON provider.\nThe filter marks the output with ``|safe``. Use it to render data inside\nHTML ``\n\n.. autofunction:: jsonify\n\n.. autofunction:: dumps\n\n.. autofunction:: dump\n\n.. autofunction:: loads\n\n.. autofunction:: load\n\n.. autoclass:: flask.json.provider.JSONProvider\n :members:\n :member-order: bysource\n\n.. autoclass:: flask.json.provider.DefaultJSONProvider\n :members:\n :member-order: bysource\n\n.. automodule:: flask.json.tag\n\n\nTemplate Rendering\n------------------\n\n.. currentmodule:: flask\n\n.. autofunction:: render_template\n\n.. autofunction:: render_template_string\n\n.. autofunction:: stream_template\n\n.. autofunction:: stream_template_string\n\n.. autofunction:: get_template_attribute\n\nConfiguration\n-------------\n\n.. autoclass:: Config\n :members:\n\n\nStream Helpers\n--------------\n\n.. autofunction:: stream_with_context\n\nUseful Internals\n----------------\n\n.. autoclass:: flask.ctx.RequestContext\n :members:\n\n.. data:: flask.globals.request_ctx\n\n The current :class:`~flask.ctx.RequestContext`. If a request context\n is not active, accessing attributes on this proxy will raise a\n ``RuntimeError``.\n\n This is an internal object that is essential to how Flask handles\n requests. Accessing this should not be needed in most cases. Most\n likely you want :data:`request` and :data:`session` instead.\n\n.. autoclass:: flask.ctx.AppContext\n :members:\n\n.. data:: flask.globals.app_ctx\n\n The current :class:`~flask.ctx.AppContext`. If an app context is not\n active, accessing attributes on this proxy will raise a\n ``RuntimeError``.\n\n This is an internal object that is essential to how Flask handles\n requests. Accessing this should not be needed in most cases. Most\n likely you want :data:`current_app` and :data:`g` instead.\n\n.. autoclass:: flask.blueprints.BlueprintSetupState\n :members:\n\n.. _core-signals-list:\n\nSignals\n-------\n\nSignals are provided by the `Blinker`_ library. See :doc:`signals` for an introduction.\n\n.. _blinker: https://blinker.readthedocs.io/\n\n.. data:: template_rendered\n\n This signal is sent when a template was successfully rendered. The\n signal is invoked with the instance of the template as `template`\n and the context as dictionary (named `context`).\n\n Example subscriber::\n\n def log_template_renders(sender, template, context, **extra):\n sender.logger.debug('Rendering template \"%s\" with context %s',\n template.name or 'string template',\n context)\n\n from flask import template_rendered\n template_rendered.connect(log_template_renders, app)\n\n.. data:: flask.before_render_template\n :noindex:\n\n This signal is sent before template rendering process. The\n signal is invoked with the instance of the template as `template`\n and the context as dictionary (named `context`).\n\n Example subscriber::\n\n def log_template_renders(sender, template, context, **extra):\n sender.logger.debug('Rendering template \"%s\" with context %s',\n template.name or 'string template',\n context)\n\n from flask import before_render_template\n before_render_template.connect(log_template_renders, app)\n\n.. data:: request_started\n\n This signal is sent when the request context is set up, before\n any request processing happens. Because the request context is already\n bound, the subscriber can access the request with the standard global\n proxies such as :class:`~flask.request`.\n\n Example subscriber::\n\n def log_request(sender, **extra):\n sender.logger.debug('Request context is set up')\n\n from flask import request_started\n request_started.connect(log_request, app)\n\n.. data:: request_finished\n\n This signal is sent right before the response is sent to the client.\n It is passed the response to be sent named `response`.\n\n Example subscriber::\n\n def log_response(sender, response, **extra):\n sender.logger.debug('Request context is about to close down. '\n 'Response: %s', response)\n\n from flask import request_finished\n request_finished.connect(log_response, app)\n\n.. data:: got_request_exception\n\n This signal is sent when an unhandled exception happens during\n request processing, including when debugging. The exception is\n passed to the subscriber as ``exception``.\n\n This signal is not sent for\n :exc:`~werkzeug.exceptions.HTTPException`, or other exceptions that\n have error handlers registered, unless the exception was raised from\n an error handler.\n\n This example shows how to do some extra logging if a theoretical\n ``SecurityException`` was raised:\n\n .. code-block:: python\n\n from flask import got_request_exception\n\n def log_security_exception(sender, exception, **extra):\n if not isinstance(exception, SecurityException):\n return\n\n security_logger.exception(\n f\"SecurityException at {request.url!r}\",\n exc_info=exception,\n )\n\n got_request_exception.connect(log_security_exception, app)\n\n.. data:: request_tearing_down\n\n This signal is sent when the request is tearing down. This is always\n called, even if an exception is caused. Currently functions listening\n to this signal are called after the regular teardown handlers, but this\n is not something you can rely on.\n\n Example subscriber::\n\n def close_db_connection(sender, **extra):\n session.close()\n\n from flask import request_tearing_down\n request_tearing_down.connect(close_db_connection, app)\n\n As of Flask 0.9, this will also be passed an `exc` keyword argument\n that has a reference to the exception that caused the teardown if\n there was one.\n\n.. data:: appcontext_tearing_down\n\n This signal is sent when the app context is tearing down. This is always\n called, even if an exception is caused. Currently functions listening\n to this signal are called after the regular teardown handlers, but this\n is not something you can rely on.\n\n Example subscriber::\n\n def close_db_connection(sender, **extra):\n session.close()\n\n from flask import appcontext_tearing_down\n appcontext_tearing_down.connect(close_db_connection, app)\n\n This will also be passed an `exc` keyword argument that has a reference\n to the exception that caused the teardown if there was one.\n\n.. data:: appcontext_pushed\n\n This signal is sent when an application context is pushed. The sender\n is the application. This is usually useful for unittests in order to\n temporarily hook in information. For instance it can be used to\n set a resource early onto the `g` object.\n\n Example usage::\n\n from contextlib import contextmanager\n from flask import appcontext_pushed\n\n @contextmanager\n def user_set(app, user):\n def handler(sender, **kwargs):\n g.user = user\n with appcontext_pushed.connected_to(handler, app):\n yield\n\n And in the testcode::\n\n def test_user_me(self):\n with user_set(app, 'john'):\n c = app.test_client()\n resp = c.get('/users/me')\n assert resp.data == 'username=john'\n\n .. versionadded:: 0.10\n\n.. data:: appcontext_popped\n\n This signal is sent when an application context is popped. The sender\n is the application. This usually falls in line with the\n :data:`appcontext_tearing_down` signal.\n\n .. versionadded:: 0.10\n\n.. data:: message_flashed\n\n This signal is sent when the application is flashing a message. The\n messages is sent as `message` keyword argument and the category as\n `category`.\n\n Example subscriber::\n\n recorded = []\n def record(sender, message, category, **extra):\n recorded.append((message, category))\n\n from flask import message_flashed\n message_flashed.connect(record, app)\n\n .. versionadded:: 0.10\n\n.. data:: signals.signals_available\n\n .. deprecated:: 2.3\n Will be removed in Flask 2.4. Signals are always available\n\n\nClass-Based Views\n-----------------\n\n.. versionadded:: 0.7\n\n.. currentmodule:: None\n\n.. autoclass:: flask.views.View\n :members:\n\n.. autoclass:: flask.views.MethodView\n :members:\n\n.. _url-route-registrations:\n\nURL Route Registrations\n-----------------------\n\nGenerally there are three ways to define rules for the routing system:\n\n1. You can use the :meth:`flask.Flask.route` decorator.\n2. You can use the :meth:`flask.Flask.add_url_rule` function.\n3. You can directly access the underlying Werkzeug routing system\n which is exposed as :attr:`flask.Flask.url_map`.\n\nVariable parts in the route can be specified with angular brackets\n(``/user/``). By default a variable part in the URL accepts any\nstring without a slash however a different converter can be specified as\nwell by using ````.\n\nVariable parts are passed to the view function as keyword arguments.\n\nThe following converters are available:\n\n=========== ===============================================\n`string` accepts any text without a slash (the default)\n`int` accepts integers\n`float` like `int` but for floating point values\n`path` like the default but also accepts slashes\n`any` matches one of the items provided\n`uuid` accepts UUID strings\n=========== ===============================================\n\nCustom converters can be defined using :attr:`flask.Flask.url_map`.\n\nHere are some examples::\n\n @app.route('/')\n def index():\n pass\n\n @app.route('/')\n def show_user(username):\n pass\n\n @app.route('/post/')\n def show_post(post_id):\n pass\n\nAn important detail to keep in mind is how Flask deals with trailing\nslashes. The idea is to keep each URL unique so the following rules\napply:\n\n1. If a rule ends with a slash and is requested without a slash by the\n user, the user is automatically redirected to the same page with a\n trailing slash attached.\n2. If a rule does not end with a trailing slash and the user requests the\n page with a trailing slash, a 404 not found is raised.\n\nThis is consistent with how web servers deal with static files. This\nalso makes it possible to use relative link targets safely.\n\nYou can also define multiple rules for the same function. They have to be\nunique however. Defaults can also be specified. Here for example is a\ndefinition for a URL that accepts an optional page::\n\n @app.route('/users/', defaults={'page': 1})\n @app.route('/users/page/')\n def show_users(page):\n pass\n\nThis specifies that ``/users/`` will be the URL for page one and\n``/users/page/N`` will be the URL for page ``N``.\n\nIf a URL contains a default value, it will be redirected to its simpler\nform with a 301 redirect. In the above example, ``/users/page/1`` will\nbe redirected to ``/users/``. If your route handles ``GET`` and ``POST``\nrequests, make sure the default route only handles ``GET``, as redirects\ncan't preserve form data. ::\n\n @app.route('/region/', defaults={'id': 1})\n @app.route('/region/', methods=['GET', 'POST'])\n def region(id):\n pass\n\nHere are the parameters that :meth:`~flask.Flask.route` and\n:meth:`~flask.Flask.add_url_rule` accept. The only difference is that\nwith the route parameter the view function is defined with the decorator\ninstead of the `view_func` parameter.\n\n=============== ==========================================================\n`rule` the URL rule as string\n`endpoint` the endpoint for the registered URL rule. Flask itself\n assumes that the name of the view function is the name\n of the endpoint if not explicitly stated.\n`view_func` the function to call when serving a request to the\n provided endpoint. If this is not provided one can\n specify the function later by storing it in the\n :attr:`~flask.Flask.view_functions` dictionary with the\n endpoint as key.\n`defaults` A dictionary with defaults for this rule. See the\n example above for how defaults work.\n`subdomain` specifies the rule for the subdomain in case subdomain\n matching is in use. If not specified the default\n subdomain is assumed.\n`**options` the options to be forwarded to the underlying\n :class:`~werkzeug.routing.Rule` object. A change to\n Werkzeug is handling of method options. methods is a list\n of methods this rule should be limited to (``GET``, ``POST``\n etc.). By default a rule just listens for ``GET`` (and\n implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is\n implicitly added and handled by the standard request\n handling. They have to be specified as keyword arguments.\n=============== ==========================================================\n\n\nView Function Options\n---------------------\n\nFor internal usage the view functions can have some attributes attached to\ncustomize behavior the view function would normally not have control over.\nThe following attributes can be provided optionally to either override\nsome defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:\n\n- `__name__`: The name of a function is by default used as endpoint. If\n endpoint is provided explicitly this value is used. Additionally this\n will be prefixed with the name of the blueprint by default which\n cannot be customized from the function itself.\n\n- `methods`: If methods are not provided when the URL rule is added,\n Flask will look on the view function object itself if a `methods`\n attribute exists. If it does, it will pull the information for the\n methods from there.\n\n- `provide_automatic_options`: if this attribute is set Flask will\n either force enable or disable the automatic implementation of the\n HTTP ``OPTIONS`` response. This can be useful when working with\n decorators that want to customize the ``OPTIONS`` response on a per-view\n basis.\n\n- `required_methods`: if this attribute is set, Flask will always add\n these methods when registering a URL rule even if the methods were\n explicitly overridden in the ``route()`` call.\n\nFull example::\n\n def index():\n if request.method == 'OPTIONS':\n # custom options handling here\n ...\n return 'Hello World!'\n index.provide_automatic_options = False\n index.methods = ['GET', 'OPTIONS']\n\n app.add_url_rule('/', index)\n\n.. versionadded:: 0.8\n The `provide_automatic_options` functionality was added.\n\nCommand Line Interface\n----------------------\n\n.. currentmodule:: flask.cli\n\n.. autoclass:: FlaskGroup\n :members:\n\n.. autoclass:: AppGroup\n :members:\n\n.. autoclass:: ScriptInfo\n :members:\n\n.. autofunction:: load_dotenv\n\n.. autofunction:: with_appcontext\n\n.. autofunction:: pass_script_info\n\n Marks a function so that an instance of :class:`ScriptInfo` is passed\n as first argument to the click callback.\n\n.. autodata:: run_command\n\n.. autodata:: shell_command\n"},{"col":0,"comment":"null","endLoc":53,"header":"@pytest.fixture\ndef app()","id":1091,"name":"app","nodeType":"Function","startLoc":46,"text":"@pytest.fixture\ndef app():\n app = Flask(\"flask_test\", root_path=os.path.dirname(__file__))\n app.config.update(\n TESTING=True,\n SECRET_KEY=\"test key\",\n )\n return app"},{"col":0,"comment":"null","endLoc":104,"header":"def test_proper_test_request_context(app)","id":1092,"name":"test_proper_test_request_context","nodeType":"Function","startLoc":63,"text":"def test_proper_test_request_context(app):\n app.config.update(SERVER_NAME=\"localhost.localdomain:5000\")\n\n @app.route(\"/\")\n def index():\n return None\n\n @app.route(\"/\", subdomain=\"foo\")\n def sub():\n return None\n\n with app.test_request_context(\"/\"):\n assert (\n flask.url_for(\"index\", _external=True)\n == \"http://localhost.localdomain:5000/\"\n )\n\n with app.test_request_context(\"/\"):\n assert (\n flask.url_for(\"sub\", _external=True)\n == \"http://foo.localhost.localdomain:5000/\"\n )\n\n # suppress Werkzeug 0.15 warning about name mismatch\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\", \"Current server name\", UserWarning, \"flask.app\"\n )\n with app.test_request_context(\n \"/\", environ_overrides={\"HTTP_HOST\": \"localhost\"}\n ):\n pass\n\n app.config.update(SERVER_NAME=\"localhost\")\n with app.test_request_context(\"/\", environ_overrides={\"SERVER_NAME\": \"localhost\"}):\n pass\n\n app.config.update(SERVER_NAME=\"localhost:80\")\n with app.test_request_context(\n \"/\", environ_overrides={\"SERVER_NAME\": \"localhost:80\"}\n ):\n pass"},{"col":0,"comment":"null","endLoc":39,"header":"def celery_init_app(app: Flask) -> Celery","id":1093,"name":"celery_init_app","nodeType":"Function","startLoc":29,"text":"def celery_init_app(app: Flask) -> Celery:\n class FlaskTask(Task):\n def __call__(self, *args: object, **kwargs: object) -> object:\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery_app = Celery(app.name, task_cls=FlaskTask)\n celery_app.config_from_object(app.config[\"CELERY\"])\n celery_app.set_default()\n app.extensions[\"celery\"] = celery_app\n return celery_app"},{"fileName":"config.py","filePath":"src/flask","id":1094,"nodeType":"File","text":"import errno\nimport json\nimport os\nimport types\nimport typing as t\n\nfrom werkzeug.utils import import_string\n\n\nclass ConfigAttribute:\n \"\"\"Makes an attribute forward to the config\"\"\"\n\n def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:\n self.__name__ = name\n self.get_converter = get_converter\n\n def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any:\n if obj is None:\n return self\n rv = obj.config[self.__name__]\n if self.get_converter is not None:\n rv = self.get_converter(rv)\n return rv\n\n def __set__(self, obj: t.Any, value: t.Any) -> None:\n obj.config[self.__name__] = value\n\n\nclass Config(dict):\n \"\"\"Works exactly like a dict but provides ways to fill it from files\n or special dictionaries. There are two common patterns to populate the\n config.\n\n Either you can fill the config from a config file::\n\n app.config.from_pyfile('yourconfig.cfg')\n\n Or alternatively you can define the configuration options in the\n module that calls :meth:`from_object` or provide an import path to\n a module that should be loaded. It is also possible to tell it to\n use the same module and with that provide the configuration values\n just before the call::\n\n DEBUG = True\n SECRET_KEY = 'development key'\n app.config.from_object(__name__)\n\n In both cases (loading from any Python file or loading from modules),\n only uppercase keys are added to the config. This makes it possible to use\n lowercase values in the config file for temporary values that are not added\n to the config or to define the config keys in the same file that implements\n the application.\n\n Probably the most interesting way to load configurations is from an\n environment variable pointing to a file::\n\n app.config.from_envvar('YOURAPPLICATION_SETTINGS')\n\n In this case before launching the application you have to set this\n environment variable to the file you want to use. On Linux and OS X\n use the export statement::\n\n export YOURAPPLICATION_SETTINGS='/path/to/config/file'\n\n On windows use `set` instead.\n\n :param root_path: path to which files are read relative from. When the\n config object is created by the application, this is\n the application's :attr:`~flask.Flask.root_path`.\n :param defaults: an optional dictionary of default values\n \"\"\"\n\n def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:\n super().__init__(defaults or {})\n self.root_path = root_path\n\n def from_envvar(self, variable_name: str, silent: bool = False) -> bool:\n \"\"\"Loads a configuration from an environment variable pointing to\n a configuration file. This is basically just a shortcut with nicer\n error messages for this line of code::\n\n app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])\n\n :param variable_name: name of the environment variable\n :param silent: set to ``True`` if you want silent failure for missing\n files.\n :return: ``True`` if the file was loaded successfully.\n \"\"\"\n rv = os.environ.get(variable_name)\n if not rv:\n if silent:\n return False\n raise RuntimeError(\n f\"The environment variable {variable_name!r} is not set\"\n \" and as such configuration could not be loaded. Set\"\n \" this variable and make it point to a configuration\"\n \" file\"\n )\n return self.from_pyfile(rv, silent=silent)\n\n def from_prefixed_env(\n self, prefix: str = \"FLASK\", *, loads: t.Callable[[str], t.Any] = json.loads\n ) -> bool:\n \"\"\"Load any environment variables that start with ``FLASK_``,\n dropping the prefix from the env key for the config key. Values\n are passed through a loading function to attempt to convert them\n to more specific types than strings.\n\n Keys are loaded in :func:`sorted` order.\n\n The default loading function attempts to parse values as any\n valid JSON type, including dicts and lists.\n\n Specific items in nested dicts can be set by separating the\n keys with double underscores (``__``). If an intermediate key\n doesn't exist, it will be initialized to an empty dict.\n\n :param prefix: Load env vars that start with this prefix,\n separated with an underscore (``_``).\n :param loads: Pass each string value to this function and use\n the returned value as the config value. If any error is\n raised it is ignored and the value remains a string. The\n default is :func:`json.loads`.\n\n .. versionadded:: 2.1\n \"\"\"\n prefix = f\"{prefix}_\"\n len_prefix = len(prefix)\n\n for key in sorted(os.environ):\n if not key.startswith(prefix):\n continue\n\n value = os.environ[key]\n\n try:\n value = loads(value)\n except Exception:\n # Keep the value as a string if loading failed.\n pass\n\n # Change to key.removeprefix(prefix) on Python >= 3.9.\n key = key[len_prefix:]\n\n if \"__\" not in key:\n # A non-nested key, set directly.\n self[key] = value\n continue\n\n # Traverse nested dictionaries with keys separated by \"__\".\n current = self\n *parts, tail = key.split(\"__\")\n\n for part in parts:\n # If an intermediate dict does not exist, create it.\n if part not in current:\n current[part] = {}\n\n current = current[part]\n\n current[tail] = value\n\n return True\n\n def from_pyfile(self, filename: str, silent: bool = False) -> bool:\n \"\"\"Updates the values in the config from a Python file. This function\n behaves as if the file was imported as module with the\n :meth:`from_object` function.\n\n :param filename: the filename of the config. This can either be an\n absolute filename or a filename relative to the\n root path.\n :param silent: set to ``True`` if you want silent failure for missing\n files.\n :return: ``True`` if the file was loaded successfully.\n\n .. versionadded:: 0.7\n `silent` parameter.\n \"\"\"\n filename = os.path.join(self.root_path, filename)\n d = types.ModuleType(\"config\")\n d.__file__ = filename\n try:\n with open(filename, mode=\"rb\") as config_file:\n exec(compile(config_file.read(), filename, \"exec\"), d.__dict__)\n except OSError as e:\n if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):\n return False\n e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n raise\n self.from_object(d)\n return True\n\n def from_object(self, obj: t.Union[object, str]) -> None:\n \"\"\"Updates the values from the given object. An object can be of one\n of the following two types:\n\n - a string: in this case the object with that name will be imported\n - an actual object reference: that object is used directly\n\n Objects are usually either modules or classes. :meth:`from_object`\n loads only the uppercase attributes of the module/class. A ``dict``\n object will not work with :meth:`from_object` because the keys of a\n ``dict`` are not attributes of the ``dict`` class.\n\n Example of module-based configuration::\n\n app.config.from_object('yourapplication.default_config')\n from yourapplication import default_config\n app.config.from_object(default_config)\n\n Nothing is done to the object before loading. If the object is a\n class and has ``@property`` attributes, it needs to be\n instantiated before being passed to this method.\n\n You should not use this function to load the actual configuration but\n rather configuration defaults. The actual config should be loaded\n with :meth:`from_pyfile` and ideally from a location not within the\n package because the package might be installed system wide.\n\n See :ref:`config-dev-prod` for an example of class-based configuration\n using :meth:`from_object`.\n\n :param obj: an import name or object\n \"\"\"\n if isinstance(obj, str):\n obj = import_string(obj)\n for key in dir(obj):\n if key.isupper():\n self[key] = getattr(obj, key)\n\n def from_file(\n self,\n filename: str,\n load: t.Callable[[t.IO[t.Any]], t.Mapping],\n silent: bool = False,\n text: bool = True,\n ) -> bool:\n \"\"\"Update the values in the config from a file that is loaded\n using the ``load`` parameter. The loaded data is passed to the\n :meth:`from_mapping` method.\n\n .. code-block:: python\n\n import json\n app.config.from_file(\"config.json\", load=json.load)\n\n import tomllib\n app.config.from_file(\"config.toml\", load=tomllib.load, text=False)\n\n :param filename: The path to the data file. This can be an\n absolute path or relative to the config root path.\n :param load: A callable that takes a file handle and returns a\n mapping of loaded data from the file.\n :type load: ``Callable[[Reader], Mapping]`` where ``Reader``\n implements a ``read`` method.\n :param silent: Ignore the file if it doesn't exist.\n :param text: Open the file in text or binary mode.\n :return: ``True`` if the file was loaded successfully.\n\n .. versionchanged:: 2.3\n The ``text`` parameter was added.\n\n .. versionadded:: 2.0\n \"\"\"\n filename = os.path.join(self.root_path, filename)\n\n try:\n with open(filename, \"r\" if text else \"rb\") as f:\n obj = load(f)\n except OSError as e:\n if silent and e.errno in (errno.ENOENT, errno.EISDIR):\n return False\n\n e.strerror = f\"Unable to load configuration file ({e.strerror})\"\n raise\n\n return self.from_mapping(obj)\n\n def from_mapping(\n self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any\n ) -> bool:\n \"\"\"Updates the config like :meth:`update` ignoring items with\n non-upper keys.\n\n :return: Always returns ``True``.\n\n .. versionadded:: 0.11\n \"\"\"\n mappings: t.Dict[str, t.Any] = {}\n if mapping is not None:\n mappings.update(mapping)\n mappings.update(kwargs)\n for key, value in mappings.items():\n if key.isupper():\n self[key] = value\n return True\n\n def get_namespace(\n self, namespace: str, lowercase: bool = True, trim_namespace: bool = True\n ) -> t.Dict[str, t.Any]:\n \"\"\"Returns a dictionary containing a subset of configuration options\n that match the specified namespace/prefix. Example usage::\n\n app.config['IMAGE_STORE_TYPE'] = 'fs'\n app.config['IMAGE_STORE_PATH'] = '/var/app/images'\n app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'\n image_store_config = app.config.get_namespace('IMAGE_STORE_')\n\n The resulting dictionary `image_store_config` would look like::\n\n {\n 'type': 'fs',\n 'path': '/var/app/images',\n 'base_url': 'http://img.website.com'\n }\n\n This is often useful when configuration options map directly to\n keyword arguments in functions or class constructors.\n\n :param namespace: a configuration namespace\n :param lowercase: a flag indicating if the keys of the resulting\n dictionary should be lowercase\n :param trim_namespace: a flag indicating if the keys of the resulting\n dictionary should not include the namespace\n\n .. versionadded:: 0.11\n \"\"\"\n rv = {}\n for k, v in self.items():\n if not k.startswith(namespace):\n continue\n if trim_namespace:\n key = k[len(namespace) :]\n else:\n key = k\n if lowercase:\n key = key.lower()\n rv[key] = v\n return rv\n\n def __repr__(self) -> str:\n return f\"<{type(self).__name__} {dict.__repr__(self)}>\"\n"},{"col":0,"comment":"null","endLoc":63,"header":"def test_uninstalled_namespace_paths(tmpdir, monkeypatch, purge_module)","id":1095,"name":"test_uninstalled_namespace_paths","nodeType":"Function","startLoc":47,"text":"def test_uninstalled_namespace_paths(tmpdir, monkeypatch, purge_module):\n def create_namespace(package):\n project = tmpdir.join(f\"project-{package}\")\n monkeypatch.syspath_prepend(str(project))\n project.join(\"namespace\").join(package).join(\"__init__.py\").write(\n \"import flask\\napp = flask.Flask(__name__)\\n\", ensure=True\n )\n return project\n\n _ = create_namespace(\"package1\")\n project2 = create_namespace(\"package2\")\n purge_module(\"namespace.package2\")\n purge_module(\"namespace\")\n\n from namespace.package2 import app\n\n assert app.instance_path == str(project2.join(\"instance\"))"},{"id":1096,"name":"fetch.html","nodeType":"TextFile","path":"examples/javascript/js_example/templates","text":"{% extends 'base.html' %}\n\n{% block intro %}\n fetch\n is the modern plain JavaScript way to make requests. It's\n supported in all modern browsers.\n{% endblock %}\n\n{% block script %}\n \n{% endblock %}\n"},{"col":0,"comment":"null","endLoc":242,"header":"def test_remove_method_from_parent(app, client)","id":1097,"name":"test_remove_method_from_parent","nodeType":"Function","startLoc":226,"text":"def test_remove_method_from_parent(app, client):\n class GetView(flask.views.MethodView):\n def get(self):\n return \"GET\"\n\n class OtherView(flask.views.MethodView):\n def post(self):\n return \"POST\"\n\n class View(GetView, OtherView):\n methods = [\"GET\"]\n\n app.add_url_rule(\"/\", view_func=View.as_view(\"index\"))\n\n assert client.get(\"/\").data == b\"GET\"\n assert client.post(\"/\").status_code == 405\n assert sorted(View.methods) == [\"GET\"]"},{"col":0,"comment":"null","endLoc":59,"header":"@pytest.fixture\ndef app_ctx(app)","id":1099,"name":"app_ctx","nodeType":"Function","startLoc":56,"text":"@pytest.fixture\ndef app_ctx(app):\n with app.app_context() as ctx:\n yield ctx"},{"col":4,"comment":"null","endLoc":219,"header":"def _check_setup_finished(self, f_name: str) -> None","id":1100,"name":"_check_setup_finished","nodeType":"Function","startLoc":211,"text":"def _check_setup_finished(self, f_name: str) -> None:\n if self._got_registered_once:\n raise AssertionError(\n f\"The setup method '{f_name}' can no longer be called on the blueprint\"\n f\" '{self.name}'. It has already been registered at least once, any\"\n \" changes will not be applied consistently.\\n\"\n \"Make sure all imports, decorators, functions, etc. needed to set up\"\n \" the blueprint are done before registering it.\"\n )"},{"id":1101,"name":"MANIFEST.in","nodeType":"TextFile","path":"examples/javascript","text":"include LICENSE.rst\ngraft js_example/templates\ngraft tests\nglobal-exclude *.pyc\n"},{"col":0,"comment":"null","endLoc":30,"header":"def b64decode(s: str | ReadableBuffer, altchars: ReadableBuffer | None = None, validate: bool = False) -> bytes","id":1102,"name":"b64decode","nodeType":"Function","startLoc":30,"text":"def b64decode(s: str | ReadableBuffer, altchars: ReadableBuffer | None = None, validate: bool = False) -> bytes: ..."},{"id":1103,"name":"examples/javascript/js_example","nodeType":"Package"},{"fileName":"__init__.py","filePath":"examples/javascript/js_example","id":1104,"nodeType":"File","text":"from flask import Flask\n\napp = Flask(__name__)\n\nfrom js_example import views # noqa: E402, F401\n"},{"col":4,"comment":"Serialize data as JSON.\n\n :param obj: The data to serialize.\n :param kwargs: May be passed to the underlying JSON library.\n ","endLoc":46,"header":"def dumps(self, obj: t.Any, **kwargs: t.Any) -> str","id":1106,"name":"dumps","nodeType":"Function","startLoc":40,"text":"def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n :param obj: The data to serialize.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n raise NotImplementedError"},{"col":4,"comment":"Serialize data as JSON and write to a file.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: May be passed to the underlying JSON library.\n ","endLoc":56,"header":"def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None","id":1107,"name":"dump","nodeType":"Function","startLoc":48,"text":"def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write to a file.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: May be passed to the underlying JSON library.\n \"\"\"\n fp.write(self.dumps(obj, **kwargs))"},{"attributeType":"null","col":0,"comment":"null","endLoc":3,"id":1108,"name":"app","nodeType":"Attribute","startLoc":3,"text":"app"},{"fileName":"test_js_example.py","filePath":"examples/javascript/tests","id":1109,"nodeType":"File","text":"import pytest\nfrom flask import template_rendered\n\n\n@pytest.mark.parametrize(\n (\"path\", \"template_name\"),\n (\n (\"/\", \"xhr.html\"),\n (\"/plain\", \"xhr.html\"),\n (\"/fetch\", \"fetch.html\"),\n (\"/jquery\", \"jquery.html\"),\n ),\n)\ndef test_index(app, client, path, template_name):\n def check(sender, template, context):\n assert template.name == template_name\n\n with template_rendered.connected_to(check, app):\n client.get(path)\n\n\n@pytest.mark.parametrize(\n (\"a\", \"b\", \"result\"), ((2, 3, 5), (2.5, 3, 5.5), (2, None, 2), (2, \"b\", 2))\n)\ndef test_add(client, a, b, result):\n response = client.post(\"/add\", data={\"a\": a, \"b\": b})\n assert response.get_json()[\"result\"] == result\n"},{"col":0,"comment":"null","endLoc":19,"header":"@pytest.mark.parametrize(\n (\"path\", \"template_name\"),\n (\n (\"/\", \"xhr.html\"),\n (\"/plain\", \"xhr.html\"),\n (\"/fetch\", \"fetch.html\"),\n (\"/jquery\", \"jquery.html\"),\n ),\n)\ndef test_index(app, client, path, template_name)","id":1110,"name":"test_index","nodeType":"Function","startLoc":5,"text":"@pytest.mark.parametrize(\n (\"path\", \"template_name\"),\n (\n (\"/\", \"xhr.html\"),\n (\"/plain\", \"xhr.html\"),\n (\"/fetch\", \"fetch.html\"),\n (\"/jquery\", \"jquery.html\"),\n ),\n)\ndef test_index(app, client, path, template_name):\n def check(sender, template, context):\n assert template.name == template_name\n\n with template_rendered.connected_to(check, app):\n client.get(path)"},{"fileName":"test_testing.py","filePath":"tests","id":1111,"nodeType":"File","text":"import click\nimport pytest\nimport werkzeug\n\nimport flask\nfrom flask import appcontext_popped\nfrom flask.cli import ScriptInfo\nfrom flask.globals import _cv_request\nfrom flask.json import jsonify\nfrom flask.testing import EnvironBuilder\nfrom flask.testing import FlaskCliRunner\n\n\ndef test_environ_defaults_from_config(app, client):\n app.config[\"SERVER_NAME\"] = \"example.com:1234\"\n app.config[\"APPLICATION_ROOT\"] = \"/foo\"\n\n @app.route(\"/\")\n def index():\n return flask.request.url\n\n ctx = app.test_request_context()\n assert ctx.request.url == \"http://example.com:1234/foo/\"\n\n rv = client.get(\"/\")\n assert rv.data == b\"http://example.com:1234/foo/\"\n\n\ndef test_environ_defaults(app, client, app_ctx, req_ctx):\n @app.route(\"/\")\n def index():\n return flask.request.url\n\n ctx = app.test_request_context()\n assert ctx.request.url == \"http://localhost/\"\n with client:\n rv = client.get(\"/\")\n assert rv.data == b\"http://localhost/\"\n\n\ndef test_environ_base_default(app, client, app_ctx):\n @app.route(\"/\")\n def index():\n flask.g.user_agent = flask.request.headers[\"User-Agent\"]\n return flask.request.remote_addr\n\n rv = client.get(\"/\")\n assert rv.data == b\"127.0.0.1\"\n assert flask.g.user_agent == f\"werkzeug/{werkzeug.__version__}\"\n\n\ndef test_environ_base_modified(app, client, app_ctx):\n @app.route(\"/\")\n def index():\n flask.g.user_agent = flask.request.headers[\"User-Agent\"]\n return flask.request.remote_addr\n\n client.environ_base[\"REMOTE_ADDR\"] = \"0.0.0.0\"\n client.environ_base[\"HTTP_USER_AGENT\"] = \"Foo\"\n rv = client.get(\"/\")\n assert rv.data == b\"0.0.0.0\"\n assert flask.g.user_agent == \"Foo\"\n\n client.environ_base[\"REMOTE_ADDR\"] = \"0.0.0.1\"\n client.environ_base[\"HTTP_USER_AGENT\"] = \"Bar\"\n rv = client.get(\"/\")\n assert rv.data == b\"0.0.0.1\"\n assert flask.g.user_agent == \"Bar\"\n\n\ndef test_client_open_environ(app, client, request):\n @app.route(\"/index\")\n def index():\n return flask.request.remote_addr\n\n builder = EnvironBuilder(app, path=\"/index\", method=\"GET\")\n request.addfinalizer(builder.close)\n\n rv = client.open(builder)\n assert rv.data == b\"127.0.0.1\"\n\n environ = builder.get_environ()\n client.environ_base[\"REMOTE_ADDR\"] = \"127.0.0.2\"\n rv = client.open(environ)\n assert rv.data == b\"127.0.0.2\"\n\n\ndef test_specify_url_scheme(app, client):\n @app.route(\"/\")\n def index():\n return flask.request.url\n\n ctx = app.test_request_context(url_scheme=\"https\")\n assert ctx.request.url == \"https://localhost/\"\n\n rv = client.get(\"/\", url_scheme=\"https\")\n assert rv.data == b\"https://localhost/\"\n\n\ndef test_path_is_url(app):\n eb = EnvironBuilder(app, \"https://example.com/\")\n assert eb.url_scheme == \"https\"\n assert eb.host == \"example.com\"\n assert eb.script_root == \"\"\n assert eb.path == \"/\"\n\n\ndef test_environbuilder_json_dumps(app):\n \"\"\"EnvironBuilder.json_dumps() takes settings from the app.\"\"\"\n app.json.ensure_ascii = False\n eb = EnvironBuilder(app, json=\"\\u20ac\")\n assert eb.input_stream.read().decode(\"utf8\") == '\"\\u20ac\"'\n\n\ndef test_blueprint_with_subdomain():\n app = flask.Flask(__name__, subdomain_matching=True)\n app.config[\"SERVER_NAME\"] = \"example.com:1234\"\n app.config[\"APPLICATION_ROOT\"] = \"/foo\"\n client = app.test_client()\n\n bp = flask.Blueprint(\"company\", __name__, subdomain=\"xxx\")\n\n @bp.route(\"/\")\n def index():\n return flask.request.url\n\n app.register_blueprint(bp)\n\n ctx = app.test_request_context(\"/\", subdomain=\"xxx\")\n assert ctx.request.url == \"http://xxx.example.com:1234/foo/\"\n\n with ctx:\n assert ctx.request.blueprint == bp.name\n\n rv = client.get(\"/\", subdomain=\"xxx\")\n assert rv.data == b\"http://xxx.example.com:1234/foo/\"\n\n\ndef test_redirect_keep_session(app, client, app_ctx):\n @app.route(\"/\", methods=[\"GET\", \"POST\"])\n def index():\n if flask.request.method == \"POST\":\n return flask.redirect(\"/getsession\")\n flask.session[\"data\"] = \"foo\"\n return \"index\"\n\n @app.route(\"/getsession\")\n def get_session():\n return flask.session.get(\"data\", \"\")\n\n with client:\n rv = client.get(\"/getsession\")\n assert rv.data == b\"\"\n\n rv = client.get(\"/\")\n assert rv.data == b\"index\"\n assert flask.session.get(\"data\") == \"foo\"\n\n rv = client.post(\"/\", data={}, follow_redirects=True)\n assert rv.data == b\"foo\"\n assert flask.session.get(\"data\") == \"foo\"\n\n rv = client.get(\"/getsession\")\n assert rv.data == b\"foo\"\n\n\ndef test_session_transactions(app, client):\n @app.route(\"/\")\n def index():\n return str(flask.session[\"foo\"])\n\n with client:\n with client.session_transaction() as sess:\n assert len(sess) == 0\n sess[\"foo\"] = [42]\n assert len(sess) == 1\n rv = client.get(\"/\")\n assert rv.data == b\"[42]\"\n with client.session_transaction() as sess:\n assert len(sess) == 1\n assert sess[\"foo\"] == [42]\n\n\ndef test_session_transactions_no_null_sessions():\n app = flask.Flask(__name__)\n\n with app.test_client() as c:\n with pytest.raises(RuntimeError) as e:\n with c.session_transaction():\n pass\n assert \"Session backend did not open a session\" in str(e.value)\n\n\ndef test_session_transactions_keep_context(app, client, req_ctx):\n client.get(\"/\")\n req = flask.request._get_current_object()\n assert req is not None\n with client.session_transaction():\n assert req is flask.request._get_current_object()\n\n\ndef test_session_transaction_needs_cookies(app):\n c = app.test_client(use_cookies=False)\n\n with pytest.raises(TypeError, match=\"Cookies are disabled.\"):\n with c.session_transaction():\n pass\n\n\ndef test_test_client_context_binding(app, client):\n app.testing = False\n\n @app.route(\"/\")\n def index():\n flask.g.value = 42\n return \"Hello World!\"\n\n @app.route(\"/other\")\n def other():\n 1 // 0\n\n with client:\n resp = client.get(\"/\")\n assert flask.g.value == 42\n assert resp.data == b\"Hello World!\"\n assert resp.status_code == 200\n\n resp = client.get(\"/other\")\n assert not hasattr(flask.g, \"value\")\n assert b\"Internal Server Error\" in resp.data\n assert resp.status_code == 500\n flask.g.value = 23\n\n try:\n flask.g.value\n except (AttributeError, RuntimeError):\n pass\n else:\n raise AssertionError(\"some kind of exception expected\")\n\n\ndef test_reuse_client(client):\n c = client\n\n with c:\n assert client.get(\"/\").status_code == 404\n\n with c:\n assert client.get(\"/\").status_code == 404\n\n\ndef test_full_url_request(app, client):\n @app.route(\"/action\", methods=[\"POST\"])\n def action():\n return \"x\"\n\n with client:\n rv = client.post(\"http://domain.com/action?vodka=42\", data={\"gin\": 43})\n assert rv.status_code == 200\n assert \"gin\" in flask.request.form\n assert \"vodka\" in flask.request.args\n\n\ndef test_json_request_and_response(app, client):\n @app.route(\"/echo\", methods=[\"POST\"])\n def echo():\n return jsonify(flask.request.get_json())\n\n with client:\n json_data = {\"drink\": {\"gin\": 1, \"tonic\": True}, \"price\": 10}\n rv = client.post(\"/echo\", json=json_data)\n\n # Request should be in JSON\n assert flask.request.is_json\n assert flask.request.get_json() == json_data\n\n # Response should be in JSON\n assert rv.status_code == 200\n assert rv.is_json\n assert rv.get_json() == json_data\n\n\ndef test_client_json_no_app_context(app, client):\n @app.route(\"/hello\", methods=[\"POST\"])\n def hello():\n return f\"Hello, {flask.request.json['name']}!\"\n\n class Namespace:\n count = 0\n\n def add(self, app):\n self.count += 1\n\n ns = Namespace()\n\n with appcontext_popped.connected_to(ns.add, app):\n rv = client.post(\"/hello\", json={\"name\": \"Flask\"})\n\n assert rv.get_data(as_text=True) == \"Hello, Flask!\"\n assert ns.count == 1\n\n\ndef test_subdomain():\n app = flask.Flask(__name__, subdomain_matching=True)\n app.config[\"SERVER_NAME\"] = \"example.com\"\n client = app.test_client()\n\n @app.route(\"/\", subdomain=\"\")\n def view(company_id):\n return company_id\n\n with app.test_request_context():\n url = flask.url_for(\"view\", company_id=\"xxx\")\n\n with client:\n response = client.get(url)\n\n assert 200 == response.status_code\n assert b\"xxx\" == response.data\n\n\ndef test_nosubdomain(app, client):\n app.config[\"SERVER_NAME\"] = \"example.com\"\n\n @app.route(\"/\")\n def view(company_id):\n return company_id\n\n with app.test_request_context():\n url = flask.url_for(\"view\", company_id=\"xxx\")\n\n with client:\n response = client.get(url)\n\n assert 200 == response.status_code\n assert b\"xxx\" == response.data\n\n\ndef test_cli_runner_class(app):\n runner = app.test_cli_runner()\n assert isinstance(runner, FlaskCliRunner)\n\n class SubRunner(FlaskCliRunner):\n pass\n\n app.test_cli_runner_class = SubRunner\n runner = app.test_cli_runner()\n assert isinstance(runner, SubRunner)\n\n\ndef test_cli_invoke(app):\n @app.cli.command(\"hello\")\n def hello_command():\n click.echo(\"Hello, World!\")\n\n runner = app.test_cli_runner()\n # invoke with command name\n result = runner.invoke(args=[\"hello\"])\n assert \"Hello\" in result.output\n # invoke with command object\n result = runner.invoke(hello_command)\n assert \"Hello\" in result.output\n\n\ndef test_cli_custom_obj(app):\n class NS:\n called = False\n\n def create_app():\n NS.called = True\n return app\n\n @app.cli.command(\"hello\")\n def hello_command():\n click.echo(\"Hello, World!\")\n\n script_info = ScriptInfo(create_app=create_app)\n runner = app.test_cli_runner()\n runner.invoke(hello_command, obj=script_info)\n assert NS.called\n\n\ndef test_client_pop_all_preserved(app, req_ctx, client):\n @app.route(\"/\")\n def index():\n # stream_with_context pushes a third context, preserved by response\n return flask.stream_with_context(\"hello\")\n\n # req_ctx fixture pushed an initial context\n with client:\n # request pushes a second request context, preserved by client\n rv = client.get(\"/\")\n\n # close the response, releasing the context held by stream_with_context\n rv.close()\n # only req_ctx fixture should still be pushed\n assert _cv_request.get(None) is req_ctx\n"},{"col":0,"comment":"null","endLoc":65,"header":"@pytest.fixture\ndef req_ctx(app)","id":1112,"name":"req_ctx","nodeType":"Function","startLoc":62,"text":"@pytest.fixture\ndef req_ctx(app):\n with app.test_request_context() as ctx:\n yield ctx"},{"fileName":"templating.py","filePath":"src/flask","id":1113,"nodeType":"File","text":"import typing as t\n\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\n\nfrom .globals import _cv_app\nfrom .globals import _cv_request\nfrom .globals import current_app\nfrom .globals import request\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nif t.TYPE_CHECKING: # pragma: no cover\n from .app import Flask\n from .scaffold import Scaffold\n\n\ndef _default_template_ctx_processor() -> t.Dict[str, t.Any]:\n \"\"\"Default template context processor. Injects `request`,\n `session` and `g`.\n \"\"\"\n appctx = _cv_app.get(None)\n reqctx = _cv_request.get(None)\n rv: t.Dict[str, t.Any] = {}\n if appctx is not None:\n rv[\"g\"] = appctx.g\n if reqctx is not None:\n rv[\"request\"] = reqctx.request\n rv[\"session\"] = reqctx.session\n return rv\n\n\nclass Environment(BaseEnvironment):\n \"\"\"Works like a regular Jinja2 environment but has some additional\n knowledge of how Flask's blueprint works so that it can prepend the\n name of the blueprint to referenced templates if necessary.\n \"\"\"\n\n def __init__(self, app: \"Flask\", **options: t.Any) -> None:\n if \"loader\" not in options:\n options[\"loader\"] = app.create_global_jinja_loader()\n BaseEnvironment.__init__(self, **options)\n self.app = app\n\n\nclass DispatchingJinjaLoader(BaseLoader):\n \"\"\"A loader that looks for templates in the application and all\n the blueprint folders.\n \"\"\"\n\n def __init__(self, app: \"Flask\") -> None:\n self.app = app\n\n def get_source( # type: ignore\n self, environment: Environment, template: str\n ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:\n if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n return self._get_source_explained(environment, template)\n return self._get_source_fast(environment, template)\n\n def _get_source_explained(\n self, environment: Environment, template: str\n ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:\n attempts = []\n rv: t.Optional[t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]]\n trv: t.Optional[\n t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]\n ] = None\n\n for srcobj, loader in self._iter_loaders(template):\n try:\n rv = loader.get_source(environment, template)\n if trv is None:\n trv = rv\n except TemplateNotFound:\n rv = None\n attempts.append((loader, srcobj, rv))\n\n from .debughelpers import explain_template_loading_attempts\n\n explain_template_loading_attempts(self.app, template, attempts)\n\n if trv is not None:\n return trv\n raise TemplateNotFound(template)\n\n def _get_source_fast(\n self, environment: Environment, template: str\n ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable]]:\n for _srcobj, loader in self._iter_loaders(template):\n try:\n return loader.get_source(environment, template)\n except TemplateNotFound:\n continue\n raise TemplateNotFound(template)\n\n def _iter_loaders(\n self, template: str\n ) -> t.Generator[t.Tuple[\"Scaffold\", BaseLoader], None, None]:\n loader = self.app.jinja_loader\n if loader is not None:\n yield self.app, loader\n\n for blueprint in self.app.iter_blueprints():\n loader = blueprint.jinja_loader\n if loader is not None:\n yield blueprint, loader\n\n def list_templates(self) -> t.List[str]:\n result = set()\n loader = self.app.jinja_loader\n if loader is not None:\n result.update(loader.list_templates())\n\n for blueprint in self.app.iter_blueprints():\n loader = blueprint.jinja_loader\n if loader is not None:\n for template in loader.list_templates():\n result.add(template)\n\n return list(result)\n\n\ndef _render(app: \"Flask\", template: Template, context: t.Dict[str, t.Any]) -> str:\n app.update_template_context(context)\n before_render_template.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n rv = template.render(context)\n template_rendered.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n return rv\n\n\ndef render_template(\n template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],\n **context: t.Any,\n) -> str:\n \"\"\"Render a template by name with the given context.\n\n :param template_name_or_list: The name of the template to render. If\n a list is given, the first name to exist will be rendered.\n :param context: The variables to make available in the template.\n \"\"\"\n app = current_app._get_current_object() # type: ignore[attr-defined]\n template = app.jinja_env.get_or_select_template(template_name_or_list)\n return _render(app, template, context)\n\n\ndef render_template_string(source: str, **context: t.Any) -> str:\n \"\"\"Render a template from the given source string with the given\n context.\n\n :param source: The source code of the template to render.\n :param context: The variables to make available in the template.\n \"\"\"\n app = current_app._get_current_object() # type: ignore[attr-defined]\n template = app.jinja_env.from_string(source)\n return _render(app, template, context)\n\n\ndef _stream(\n app: \"Flask\", template: Template, context: t.Dict[str, t.Any]\n) -> t.Iterator[str]:\n app.update_template_context(context)\n before_render_template.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n\n def generate() -> t.Iterator[str]:\n yield from template.generate(context)\n template_rendered.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n\n rv = generate()\n\n # If a request context is active, keep it while generating.\n if request:\n rv = stream_with_context(rv)\n\n return rv\n\n\ndef stream_template(\n template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],\n **context: t.Any,\n) -> t.Iterator[str]:\n \"\"\"Render a template by name with the given context as a stream.\n This returns an iterator of strings, which can be used as a\n streaming response from a view.\n\n :param template_name_or_list: The name of the template to render. If\n a list is given, the first name to exist will be rendered.\n :param context: The variables to make available in the template.\n\n .. versionadded:: 2.2\n \"\"\"\n app = current_app._get_current_object() # type: ignore[attr-defined]\n template = app.jinja_env.get_or_select_template(template_name_or_list)\n return _stream(app, template, context)\n\n\ndef stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:\n \"\"\"Render a template from the given source string with the given\n context as a stream. This returns an iterator of strings, which can\n be used as a streaming response from a view.\n\n :param source: The source code of the template to render.\n :param context: The variables to make available in the template.\n\n .. versionadded:: 2.2\n \"\"\"\n app = current_app._get_current_object() # type: ignore[attr-defined]\n template = app.jinja_env.from_string(source)\n return _stream(app, template, context)\n"},{"col":0,"comment":"null","endLoc":29,"header":"def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes","id":1114,"name":"b64encode","nodeType":"Function","startLoc":29,"text":"def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: ..."},{"col":4,"comment":"The registered names of the current blueprint upwards through\n parent blueprints.\n\n This will be an empty list if there is no current blueprint, or\n if URL matching failed.\n\n .. versionadded:: 2.0.1\n ","endLoc":109,"header":"@property\n def blueprints(self) -> t.List[str]","id":1115,"name":"blueprints","nodeType":"Function","startLoc":94,"text":"@property\n def blueprints(self) -> t.List[str]:\n \"\"\"The registered names of the current blueprint upwards through\n parent blueprints.\n\n This will be an empty list if there is no current blueprint, or\n if URL matching failed.\n\n .. versionadded:: 2.0.1\n \"\"\"\n name = self.blueprint\n\n if name is None:\n return []\n\n return _split_blueprint_path(name)"},{"className":"Environment","col":0,"comment":"The core component of Jinja is the `Environment`. It contains\n important shared variables like configuration, filters, tests,\n globals and others. Instances of this class may be modified if\n they are not shared and if no template was loaded so far.\n Modifications on environments after the first template was loaded\n will lead to surprising effects and undefined behavior.\n\n Here are the possible initialization parameters:\n\n `block_start_string`\n The string marking the beginning of a block. Defaults to ``'{%'``.\n\n `block_end_string`\n The string marking the end of a block. Defaults to ``'%}'``.\n\n `variable_start_string`\n The string marking the beginning of a print statement.\n Defaults to ``'{{'``.\n\n `variable_end_string`\n The string marking the end of a print statement. Defaults to\n ``'}}'``.\n\n `comment_start_string`\n The string marking the beginning of a comment. Defaults to ``'{#'``.\n\n `comment_end_string`\n The string marking the end of a comment. Defaults to ``'#}'``.\n\n `line_statement_prefix`\n If given and a string, this will be used as prefix for line based\n statements. See also :ref:`line-statements`.\n\n `line_comment_prefix`\n If given and a string, this will be used as prefix for line based\n comments. See also :ref:`line-statements`.\n\n .. versionadded:: 2.2\n\n `trim_blocks`\n If this is set to ``True`` the first newline after a block is\n removed (block, not variable tag!). Defaults to `False`.\n\n `lstrip_blocks`\n If this is set to ``True`` leading spaces and tabs are stripped\n from the start of a line to a block. Defaults to `False`.\n\n `newline_sequence`\n The sequence that starts a newline. Must be one of ``'\\r'``,\n ``'\\n'`` or ``'\\r\\n'``. The default is ``'\\n'`` which is a\n useful default for Linux and OS X systems as well as web\n applications.\n\n `keep_trailing_newline`\n Preserve the trailing newline when rendering templates.\n The default is ``False``, which causes a single newline,\n if present, to be stripped from the end of the template.\n\n .. versionadded:: 2.7\n\n `extensions`\n List of Jinja extensions to use. This can either be import paths\n as strings or extension classes. For more information have a\n look at :ref:`the extensions documentation `.\n\n `optimized`\n should the optimizer be enabled? Default is ``True``.\n\n `undefined`\n :class:`Undefined` or a subclass of it that is used to represent\n undefined values in the template.\n\n `finalize`\n A callable that can be used to process the result of a variable\n expression before it is output. For example one can convert\n ``None`` implicitly into an empty string here.\n\n `autoescape`\n If set to ``True`` the XML/HTML autoescaping feature is enabled by\n default. For more details about autoescaping see\n :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also\n be a callable that is passed the template name and has to\n return ``True`` or ``False`` depending on autoescape should be\n enabled by default.\n\n .. versionchanged:: 2.4\n `autoescape` can now be a function\n\n `loader`\n The template loader for this environment.\n\n `cache_size`\n The size of the cache. Per default this is ``400`` which means\n that if more than 400 templates are loaded the loader will clean\n out the least recently used template. If the cache size is set to\n ``0`` templates are recompiled all the time, if the cache size is\n ``-1`` the cache will not be cleaned.\n\n .. versionchanged:: 2.8\n The cache size was increased to 400 from a low 50.\n\n `auto_reload`\n Some loaders load templates from locations where the template\n sources may change (ie: file system or database). If\n ``auto_reload`` is set to ``True`` (default) every time a template is\n requested the loader checks if the source changed and if yes, it\n will reload the template. For higher performance it's possible to\n disable that.\n\n `bytecode_cache`\n If set to a bytecode cache object, this object will provide a\n cache for the internal Jinja bytecode so that templates don't\n have to be parsed if they were not changed.\n\n See :ref:`bytecode-cache` for more information.\n\n `enable_async`\n If set to true this enables async template execution which allows\n you to take advantage of newer Python features. This requires\n Python 3.6 or later.\n ","endLoc":947,"id":1116,"nodeType":"Class","startLoc":141,"text":"class Environment(object):\n r\"\"\"The core component of Jinja is the `Environment`. It contains\n important shared variables like configuration, filters, tests,\n globals and others. Instances of this class may be modified if\n they are not shared and if no template was loaded so far.\n Modifications on environments after the first template was loaded\n will lead to surprising effects and undefined behavior.\n\n Here are the possible initialization parameters:\n\n `block_start_string`\n The string marking the beginning of a block. Defaults to ``'{%'``.\n\n `block_end_string`\n The string marking the end of a block. Defaults to ``'%}'``.\n\n `variable_start_string`\n The string marking the beginning of a print statement.\n Defaults to ``'{{'``.\n\n `variable_end_string`\n The string marking the end of a print statement. Defaults to\n ``'}}'``.\n\n `comment_start_string`\n The string marking the beginning of a comment. Defaults to ``'{#'``.\n\n `comment_end_string`\n The string marking the end of a comment. Defaults to ``'#}'``.\n\n `line_statement_prefix`\n If given and a string, this will be used as prefix for line based\n statements. See also :ref:`line-statements`.\n\n `line_comment_prefix`\n If given and a string, this will be used as prefix for line based\n comments. See also :ref:`line-statements`.\n\n .. versionadded:: 2.2\n\n `trim_blocks`\n If this is set to ``True`` the first newline after a block is\n removed (block, not variable tag!). Defaults to `False`.\n\n `lstrip_blocks`\n If this is set to ``True`` leading spaces and tabs are stripped\n from the start of a line to a block. Defaults to `False`.\n\n `newline_sequence`\n The sequence that starts a newline. Must be one of ``'\\r'``,\n ``'\\n'`` or ``'\\r\\n'``. The default is ``'\\n'`` which is a\n useful default for Linux and OS X systems as well as web\n applications.\n\n `keep_trailing_newline`\n Preserve the trailing newline when rendering templates.\n The default is ``False``, which causes a single newline,\n if present, to be stripped from the end of the template.\n\n .. versionadded:: 2.7\n\n `extensions`\n List of Jinja extensions to use. This can either be import paths\n as strings or extension classes. For more information have a\n look at :ref:`the extensions documentation `.\n\n `optimized`\n should the optimizer be enabled? Default is ``True``.\n\n `undefined`\n :class:`Undefined` or a subclass of it that is used to represent\n undefined values in the template.\n\n `finalize`\n A callable that can be used to process the result of a variable\n expression before it is output. For example one can convert\n ``None`` implicitly into an empty string here.\n\n `autoescape`\n If set to ``True`` the XML/HTML autoescaping feature is enabled by\n default. For more details about autoescaping see\n :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also\n be a callable that is passed the template name and has to\n return ``True`` or ``False`` depending on autoescape should be\n enabled by default.\n\n .. versionchanged:: 2.4\n `autoescape` can now be a function\n\n `loader`\n The template loader for this environment.\n\n `cache_size`\n The size of the cache. Per default this is ``400`` which means\n that if more than 400 templates are loaded the loader will clean\n out the least recently used template. If the cache size is set to\n ``0`` templates are recompiled all the time, if the cache size is\n ``-1`` the cache will not be cleaned.\n\n .. versionchanged:: 2.8\n The cache size was increased to 400 from a low 50.\n\n `auto_reload`\n Some loaders load templates from locations where the template\n sources may change (ie: file system or database). If\n ``auto_reload`` is set to ``True`` (default) every time a template is\n requested the loader checks if the source changed and if yes, it\n will reload the template. For higher performance it's possible to\n disable that.\n\n `bytecode_cache`\n If set to a bytecode cache object, this object will provide a\n cache for the internal Jinja bytecode so that templates don't\n have to be parsed if they were not changed.\n\n See :ref:`bytecode-cache` for more information.\n\n `enable_async`\n If set to true this enables async template execution which allows\n you to take advantage of newer Python features. This requires\n Python 3.6 or later.\n \"\"\"\n\n #: if this environment is sandboxed. Modifying this variable won't make\n #: the environment sandboxed though. For a real sandboxed environment\n #: have a look at jinja2.sandbox. This flag alone controls the code\n #: generation by the compiler.\n sandboxed = False\n\n #: True if the environment is just an overlay\n overlayed = False\n\n #: the environment this environment is linked to if it is an overlay\n linked_to = None\n\n #: shared environments have this set to `True`. A shared environment\n #: must not be modified\n shared = False\n\n #: the class that is used for code generation. See\n #: :class:`~jinja2.compiler.CodeGenerator` for more information.\n code_generator_class = CodeGenerator\n\n #: the context class thatis used for templates. See\n #: :class:`~jinja2.runtime.Context` for more information.\n context_class = Context\n\n def __init__(\n self,\n block_start_string=BLOCK_START_STRING,\n block_end_string=BLOCK_END_STRING,\n variable_start_string=VARIABLE_START_STRING,\n variable_end_string=VARIABLE_END_STRING,\n comment_start_string=COMMENT_START_STRING,\n comment_end_string=COMMENT_END_STRING,\n line_statement_prefix=LINE_STATEMENT_PREFIX,\n line_comment_prefix=LINE_COMMENT_PREFIX,\n trim_blocks=TRIM_BLOCKS,\n lstrip_blocks=LSTRIP_BLOCKS,\n newline_sequence=NEWLINE_SEQUENCE,\n keep_trailing_newline=KEEP_TRAILING_NEWLINE,\n extensions=(),\n optimized=True,\n undefined=Undefined,\n finalize=None,\n autoescape=False,\n loader=None,\n cache_size=400,\n auto_reload=True,\n bytecode_cache=None,\n enable_async=False,\n ):\n # !!Important notice!!\n # The constructor accepts quite a few arguments that should be\n # passed by keyword rather than position. However it's important to\n # not change the order of arguments because it's used at least\n # internally in those cases:\n # - spontaneous environments (i18n extension and Template)\n # - unittests\n # If parameter changes are required only add parameters at the end\n # and don't change the arguments (or the defaults!) of the arguments\n # existing already.\n\n # lexer / parser information\n self.block_start_string = block_start_string\n self.block_end_string = block_end_string\n self.variable_start_string = variable_start_string\n self.variable_end_string = variable_end_string\n self.comment_start_string = comment_start_string\n self.comment_end_string = comment_end_string\n self.line_statement_prefix = line_statement_prefix\n self.line_comment_prefix = line_comment_prefix\n self.trim_blocks = trim_blocks\n self.lstrip_blocks = lstrip_blocks\n self.newline_sequence = newline_sequence\n self.keep_trailing_newline = keep_trailing_newline\n\n # runtime information\n self.undefined = undefined\n self.optimized = optimized\n self.finalize = finalize\n self.autoescape = autoescape\n\n # defaults\n self.filters = DEFAULT_FILTERS.copy()\n self.tests = DEFAULT_TESTS.copy()\n self.globals = DEFAULT_NAMESPACE.copy()\n\n # set the loader provided\n self.loader = loader\n self.cache = create_cache(cache_size)\n self.bytecode_cache = bytecode_cache\n self.auto_reload = auto_reload\n\n # configurable policies\n self.policies = DEFAULT_POLICIES.copy()\n\n # load extensions\n self.extensions = load_extensions(self, extensions)\n\n self.enable_async = enable_async\n self.is_async = self.enable_async and have_async_gen\n if self.is_async:\n # runs patch_all() to enable async support\n from . import asyncsupport # noqa: F401\n\n _environment_sanity_check(self)\n\n def add_extension(self, extension):\n \"\"\"Adds an extension after the environment was created.\n\n .. versionadded:: 2.5\n \"\"\"\n self.extensions.update(load_extensions(self, [extension]))\n\n def extend(self, **attributes):\n \"\"\"Add the items to the instance of the environment if they do not exist\n yet. This is used by :ref:`extensions ` to register\n callbacks and configuration values without breaking inheritance.\n \"\"\"\n for key, value in iteritems(attributes):\n if not hasattr(self, key):\n setattr(self, key, value)\n\n def overlay(\n self,\n block_start_string=missing,\n block_end_string=missing,\n variable_start_string=missing,\n variable_end_string=missing,\n comment_start_string=missing,\n comment_end_string=missing,\n line_statement_prefix=missing,\n line_comment_prefix=missing,\n trim_blocks=missing,\n lstrip_blocks=missing,\n extensions=missing,\n optimized=missing,\n undefined=missing,\n finalize=missing,\n autoescape=missing,\n loader=missing,\n cache_size=missing,\n auto_reload=missing,\n bytecode_cache=missing,\n ):\n \"\"\"Create a new overlay environment that shares all the data with the\n current environment except for cache and the overridden attributes.\n Extensions cannot be removed for an overlayed environment. An overlayed\n environment automatically gets all the extensions of the environment it\n is linked to plus optional extra extensions.\n\n Creating overlays should happen after the initial environment was set\n up completely. Not all attributes are truly linked, some are just\n copied over so modifications on the original environment may not shine\n through.\n \"\"\"\n args = dict(locals())\n del args[\"self\"], args[\"cache_size\"], args[\"extensions\"]\n\n rv = object.__new__(self.__class__)\n rv.__dict__.update(self.__dict__)\n rv.overlayed = True\n rv.linked_to = self\n\n for key, value in iteritems(args):\n if value is not missing:\n setattr(rv, key, value)\n\n if cache_size is not missing:\n rv.cache = create_cache(cache_size)\n else:\n rv.cache = copy_cache(self.cache)\n\n rv.extensions = {}\n for key, value in iteritems(self.extensions):\n rv.extensions[key] = value.bind(rv)\n if extensions is not missing:\n rv.extensions.update(load_extensions(rv, extensions))\n\n return _environment_sanity_check(rv)\n\n lexer = property(get_lexer, doc=\"The lexer for this environment.\")\n\n def iter_extensions(self):\n \"\"\"Iterates over the extensions by priority.\"\"\"\n return iter(sorted(self.extensions.values(), key=lambda x: x.priority))\n\n def getitem(self, obj, argument):\n \"\"\"Get an item or attribute of an object but prefer the item.\"\"\"\n try:\n return obj[argument]\n except (AttributeError, TypeError, LookupError):\n if isinstance(argument, string_types):\n try:\n attr = str(argument)\n except Exception:\n pass\n else:\n try:\n return getattr(obj, attr)\n except AttributeError:\n pass\n return self.undefined(obj=obj, name=argument)\n\n def getattr(self, obj, attribute):\n \"\"\"Get an item or attribute of an object but prefer the attribute.\n Unlike :meth:`getitem` the attribute *must* be a bytestring.\n \"\"\"\n try:\n return getattr(obj, attribute)\n except AttributeError:\n pass\n try:\n return obj[attribute]\n except (TypeError, LookupError, AttributeError):\n return self.undefined(obj=obj, name=attribute)\n\n def call_filter(\n self, name, value, args=None, kwargs=None, context=None, eval_ctx=None\n ):\n \"\"\"Invokes a filter on a value the same way the compiler does it.\n\n Note that on Python 3 this might return a coroutine in case the\n filter is running from an environment in async mode and the filter\n supports async execution. It's your responsibility to await this\n if needed.\n\n .. versionadded:: 2.7\n \"\"\"\n func = self.filters.get(name)\n if func is None:\n fail_for_missing_callable(\"no filter named %r\", name)\n args = [value] + list(args or ())\n if getattr(func, \"contextfilter\", False) is True:\n if context is None:\n raise TemplateRuntimeError(\n \"Attempted to invoke context filter without context\"\n )\n args.insert(0, context)\n elif getattr(func, \"evalcontextfilter\", False) is True:\n if eval_ctx is None:\n if context is not None:\n eval_ctx = context.eval_ctx\n else:\n eval_ctx = EvalContext(self)\n args.insert(0, eval_ctx)\n elif getattr(func, \"environmentfilter\", False) is True:\n args.insert(0, self)\n return func(*args, **(kwargs or {}))\n\n def call_test(self, name, value, args=None, kwargs=None):\n \"\"\"Invokes a test on a value the same way the compiler does it.\n\n .. versionadded:: 2.7\n \"\"\"\n func = self.tests.get(name)\n if func is None:\n fail_for_missing_callable(\"no test named %r\", name)\n return func(value, *(args or ()), **(kwargs or {}))\n\n @internalcode\n def parse(self, source, name=None, filename=None):\n \"\"\"Parse the sourcecode and return the abstract syntax tree. This\n tree of nodes is used by the compiler to convert the template into\n executable source- or bytecode. This is useful for debugging or to\n extract information from templates.\n\n If you are :ref:`developing Jinja extensions `\n this gives you a good overview of the node tree generated.\n \"\"\"\n try:\n return self._parse(source, name, filename)\n except TemplateSyntaxError:\n self.handle_exception(source=source)\n\n def _parse(self, source, name, filename):\n \"\"\"Internal parsing function used by `parse` and `compile`.\"\"\"\n return Parser(self, source, name, encode_filename(filename)).parse()\n\n def lex(self, source, name=None, filename=None):\n \"\"\"Lex the given sourcecode and return a generator that yields\n tokens as tuples in the form ``(lineno, token_type, value)``.\n This can be useful for :ref:`extension development `\n and debugging templates.\n\n This does not perform preprocessing. If you want the preprocessing\n of the extensions to be applied you have to filter source through\n the :meth:`preprocess` method.\n \"\"\"\n source = text_type(source)\n try:\n return self.lexer.tokeniter(source, name, filename)\n except TemplateSyntaxError:\n self.handle_exception(source=source)\n\n def preprocess(self, source, name=None, filename=None):\n \"\"\"Preprocesses the source with all extensions. This is automatically\n called for all parsing and compiling methods but *not* for :meth:`lex`\n because there you usually only want the actual source tokenized.\n \"\"\"\n return reduce(\n lambda s, e: e.preprocess(s, name, filename),\n self.iter_extensions(),\n text_type(source),\n )\n\n def _tokenize(self, source, name, filename=None, state=None):\n \"\"\"Called by the parser to do the preprocessing and filtering\n for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.\n \"\"\"\n source = self.preprocess(source, name, filename)\n stream = self.lexer.tokenize(source, name, filename, state)\n for ext in self.iter_extensions():\n stream = ext.filter_stream(stream)\n if not isinstance(stream, TokenStream):\n stream = TokenStream(stream, name, filename)\n return stream\n\n def _generate(self, source, name, filename, defer_init=False):\n \"\"\"Internal hook that can be overridden to hook a different generate\n method in.\n\n .. versionadded:: 2.5\n \"\"\"\n return generate(\n source,\n self,\n name,\n filename,\n defer_init=defer_init,\n optimized=self.optimized,\n )\n\n def _compile(self, source, filename):\n \"\"\"Internal hook that can be overridden to hook a different compile\n method in.\n\n .. versionadded:: 2.5\n \"\"\"\n return compile(source, filename, \"exec\")\n\n @internalcode\n def compile(self, source, name=None, filename=None, raw=False, defer_init=False):\n \"\"\"Compile a node or template source code. The `name` parameter is\n the load name of the template after it was joined using\n :meth:`join_path` if necessary, not the filename on the file system.\n the `filename` parameter is the estimated filename of the template on\n the file system. If the template came from a database or memory this\n can be omitted.\n\n The return value of this method is a python code object. If the `raw`\n parameter is `True` the return value will be a string with python\n code equivalent to the bytecode returned otherwise. This method is\n mainly used internally.\n\n `defer_init` is use internally to aid the module code generator. This\n causes the generated code to be able to import without the global\n environment variable to be set.\n\n .. versionadded:: 2.4\n `defer_init` parameter added.\n \"\"\"\n source_hint = None\n try:\n if isinstance(source, string_types):\n source_hint = source\n source = self._parse(source, name, filename)\n source = self._generate(source, name, filename, defer_init=defer_init)\n if raw:\n return source\n if filename is None:\n filename = \"