File size: 88,009 Bytes
25f22bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 |
======================== CODE SNIPPETS ======================== TITLE: Implementing Content Security Policy (CSP) in Flask DESCRIPTION: Sets the Content Security Policy header to control resource loading, mitigating XSS and data injection attacks. The example shows a strict policy allowing resources only from the same origin. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_5 LANGUAGE: Python CODE: ``` response.headers['Content-Security-Policy'] = "default-src 'self'" ``` ---------------------------------------- TITLE: Setting Secure and HttpOnly Cookies in Flask DESCRIPTION: Demonstrates how to set a secure, HttpOnly, and SameSite=Lax cookie in Flask, enhancing security by preventing client-side script access and cross-site request forgery. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_9 LANGUAGE: python CODE: ``` response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax') ``` ---------------------------------------- TITLE: Configuring Secure Session Cookie Options in Flask DESCRIPTION: Demonstrates how to configure Flask's session cookie with 'Secure', 'HttpOnly', and 'SameSite' options for enhanced security. 'Secure' limits cookies to HTTPS, 'HttpOnly' prevents JavaScript access, and 'SameSite='Lax'' restricts cookie sending with CSRF-prone requests. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_8 LANGUAGE: Python CODE: ``` app.config.update( SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Lax' ) ``` ---------------------------------------- TITLE: XSS Attack Example: Javascript URI in Anchor Tag DESCRIPTION: Shows how a javascript: URI in an <a> tag's href attribute can lead to a Cross-Site Scripting (XSS) vulnerability. Browsers will execute such URIs when clicked if not properly secured, for example, by setting a Content Security Policy (CSP). SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_3 LANGUAGE: html CODE: ``` <a href="{{ value }}">click here</a> <a href="javascript:alert('unsafe');">click here</a> ``` ---------------------------------------- TITLE: Filtering Backspace Characters from User Input in Python DESCRIPTION: Provides a Python example for removing backspace characters (\b) from a string. This is a security measure to prevent malicious code from rendering differently in HTML than when pasted into a terminal, although modern terminals often warn about such characters. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_12 LANGUAGE: python CODE: ``` body = body.replace("\b", "") ``` ---------------------------------------- TITLE: itsdangerous.TimedSerializer Class DESCRIPTION: A class from the `itsdangerous` library used to sign and validate values with a time-based signature. It is suitable for securing cookie values or other data that requires integrity and expiration. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_16 LANGUAGE: APIDOC CODE: ``` itsdangerous.TimedSerializer ``` ---------------------------------------- TITLE: Mitigating Clickjacking with X-Frame-Options in Flask DESCRIPTION: Sets the X-Frame-Options header to prevent external sites from embedding the application in an iframe, protecting against clickjacking attacks. 'SAMEORIGIN' allows embedding only by pages from the same origin. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_7 LANGUAGE: Python CODE: ``` response.headers['X-Frame-Options'] = 'SAMEORIGIN' ``` ---------------------------------------- TITLE: Preventing MIME Type Sniffing with X-Content-Type-Options in Flask DESCRIPTION: Adds the X-Content-Type-Options header with 'nosniff' to prevent browsers from guessing content types, which can lead to XSS vulnerabilities. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_6 LANGUAGE: Python CODE: ``` response.headers['X-Content-Type-Options'] = 'nosniff' ``` ---------------------------------------- TITLE: Setting HTTP Strict Transport Security (HSTS) Header in Flask DESCRIPTION: Configures the HSTS header to force browsers to use HTTPS, preventing man-in-the-middle (MITM) attacks. The 'max-age' directive specifies how long the browser should remember to enforce HTTPS, and 'includeSubDomains' applies the policy to subdomains. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_4 LANGUAGE: Python CODE: ``` response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' ``` ---------------------------------------- TITLE: Flask Response.set_cookie Method DESCRIPTION: Sets a cookie on the response object. Allows specifying various attributes to control cookie behavior and security. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_13 LANGUAGE: APIDOC CODE: ``` response.set_cookie( key: str, value: str = '', max_age: Optional[int] = None, # Cookie expiration in seconds expires: Optional[Union[int, datetime]] = None, # Cookie expiration date/time path: str = '/', domain: Optional[str] = None, secure: bool = False, # Transmit cookie only over HTTPS httponly: bool = False, # Prevent client-side script access samesite: Optional[str] = None, # 'Lax', 'Strict', or 'None' **kwargs # Additional cookie attributes ) ``` ---------------------------------------- TITLE: Configuring and Using Permanent Sessions in Flask DESCRIPTION: Illustrates how to configure the `PERMANENT_SESSION_LIFETIME` for Flask sessions and how to mark a session as permanent within a route, ensuring it persists for the configured duration. This also impacts the cryptographic signature validation. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_11 LANGUAGE: python CODE: ``` app.config.update( PERMANENT_SESSION_LIFETIME=600 ) @app.route('/login', methods=['POST']) def login(): ... session.clear() session['user_id'] = user.id session.permanent = True ... ``` ---------------------------------------- TITLE: Preventing XSS with Jinja Attribute Quoting DESCRIPTION: Demonstrates the importance of quoting attributes when using Jinja expressions in HTML to prevent Cross-Site Scripting (XSS) vulnerabilities. Unquoted attributes can allow attackers to inject malicious JavaScript handlers. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_1 LANGUAGE: html+jinja CODE: ``` <input value="{{ value }}"> ``` ---------------------------------------- TITLE: Flask File Upload: Secure Filename DESCRIPTION: Illustrates how to securely save an uploaded file using `werkzeug.utils.secure_filename` to prevent path traversal vulnerabilities. It's crucial to sanitize client-provided filenames before using them on the server. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_21 LANGUAGE: python CODE: ``` from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['the_file'] file.save(f"/var/www/uploads/{secure_filename(file.filename)}") ... ``` ---------------------------------------- TITLE: Generating Flask Secret Key - Shell DESCRIPTION: Command line example using Python's `secrets` module to generate a secure hexadecimal string suitable for use as a Flask `SECRET_KEY`. SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_4 LANGUAGE: text CODE: ``` $ python -c 'import secrets; print(secrets.token_hex())' ``` ---------------------------------------- TITLE: Using MarkupSafe for HTML Escaping and Unescaping DESCRIPTION: Demonstrates the `markupsafe.Markup` class for handling HTML strings securely in Python. It illustrates how to combine safe and unsafe strings, explicitly escape potentially malicious HTML, and strip HTML tags from text, crucial for preventing Cross-Site Scripting (XSS) vulnerabilities. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_14 LANGUAGE: python CODE: ``` from markupsafe import Markup >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>' Markup('<strong>Hello <blink>hacker</blink>!</strong>') >>> Markup.escape('<blink>hacker</blink>') Markup('<blink>hacker</blink>') >>> Markup('<em>Marked up</em> » HTML').striptags() 'Marked up » HTML' ``` ---------------------------------------- TITLE: Flask Session.permanent Attribute DESCRIPTION: A boolean attribute of the Flask session object. If set to `True`, the session cookie will persist for the duration specified by `PERMANENT_SESSION_LIFETIME`. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_14 LANGUAGE: APIDOC CODE: ``` session.permanent: bool ``` ---------------------------------------- TITLE: XSS Attack Example: Malicious Attribute Injection DESCRIPTION: Illustrates a potential Cross-Site Scripting (XSS) attack where an attacker injects a malicious JavaScript handler into an unquoted HTML attribute. This code snippet shows how onmouseover=alert(document.cookie) could be injected to execute arbitrary JavaScript. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_2 LANGUAGE: html CODE: ``` onmouseover=alert(document.cookie) ``` ---------------------------------------- TITLE: Werkzeug secure_filename Function DESCRIPTION: Documentation for the werkzeug.utils.secure_filename function. This function is critical for sanitizing user-provided filenames before saving them to the filesystem, preventing security vulnerabilities like directory traversal by removing unsafe characters and path components. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_6 LANGUAGE: APIDOC CODE: ``` werkzeug.utils.secure_filename(filename: str) -> str filename: str - The filename string to secure. Returns: str - A secured version of the filename, safe for storage on a filesystem. Description: Secures a filename to prevent directory traversal and other filesystem-related attacks by removing unsafe characters. ``` ---------------------------------------- TITLE: Flask Resource Use Configuration for DoS Prevention DESCRIPTION: Details Flask's configuration options to mitigate Denial of Service (DoS) attacks by controlling resource consumption per request. These settings help limit the amount of data, form memory, and form parts processed, preventing excessive resource usage. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_0 LANGUAGE: APIDOC CODE: ``` Configuration Options: - MAX_CONTENT_LENGTH (or Request.max_content_length): Controls maximum data read from a request. Not set by default, but blocks truly unlimited streams unless WSGI server supports it. - MAX_FORM_MEMORY_SIZE (or Request.max_form_memory_size): Controls maximum size of non-file multipart/form-data fields. Default: 500kB. - MAX_FORM_PARTS (or Request.max_form_parts): Controls maximum number of multipart/form-data fields parsed. Default: 1000. Combined with default max_form_memory_size, a form can occupy at most 500MB. ``` ---------------------------------------- TITLE: Generate production secret key for Flask DESCRIPTION: Provides a Python command to generate a strong, random hexadecimal string suitable for use as the SECRET_KEY in a Flask production environment. This key is vital for security, protecting session cookies and other sensitive data. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_4 LANGUAGE: shell CODE: ``` $ python -c 'import secrets; print(secrets.token_hex())' ``` ---------------------------------------- TITLE: Flask PERMANENT_SESSION_LIFETIME Configuration DESCRIPTION: A configuration key in Flask's `app.config` that defines the lifetime of a permanent session cookie in seconds. This value is also used by Flask's default cookie implementation to validate the cryptographic signature, mitigating replay attacks. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_15 LANGUAGE: APIDOC CODE: ``` app.config['PERMANENT_SESSION_LIFETIME']: int (seconds) ``` ---------------------------------------- TITLE: Setting an Expiring Cookie in Flask DESCRIPTION: Shows how to set a cookie that expires after a specified duration (e.g., 10 minutes) using the `max_age` parameter. If neither `Expires` nor `Max-Age` is set, the cookie will be removed when the browser is closed. SOURCE: https://github.com/pallets/flask/blob/main/docs/web-security.rst#_snippet_10 LANGUAGE: python CODE: ``` # cookie expires after 10 minutes response.set_cookie('snakes', '3', max_age=600) ``` ---------------------------------------- TITLE: Configure Flask SECRET_KEY in production DESCRIPTION: Example of how to set the generated SECRET_KEY within the 'config.py' file, located in the Flask instance folder. This configuration overrides the development key and is essential for securing the application in production. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_5 LANGUAGE: python CODE: ``` SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' ``` ---------------------------------------- TITLE: APIDOC: `tempfile.mkstemp` Function DESCRIPTION: Documentation for the `tempfile.mkstemp` function, which creates and opens a temporary file securely. It returns a tuple containing an OS-level handle (file descriptor) to the file and its absolute path. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_3 LANGUAGE: APIDOC CODE: ``` tempfile.mkstemp() -> (fd: int, path: str) fd: The file descriptor of the temporary file. path: The absolute path to the temporary file. ``` ---------------------------------------- TITLE: Run mod_wsgi-express on privileged port with user/group drop DESCRIPTION: This example demonstrates how to run `mod_wsgi-express` as a root user to bind to privileged ports (e.g., 80) while securely dropping permissions to a non-root user and group for the worker processes, enhancing security. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.rst#_snippet_3 LANGUAGE: text CODE: ``` $ sudo /home/hello/.venv/bin/mod_wsgi-express start-server \ /home/hello/wsgi.py \ --user hello --group hello --port 80 --processes 4 ``` ---------------------------------------- TITLE: Configure Flask to Trust Proxy Headers with ProxyFix Middleware DESCRIPTION: This Python snippet demonstrates how to apply the ProxyFix middleware from Werkzeug to a Flask application's WSGI app. It configures Flask to trust X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, and X-Forwarded-Prefix headers, which are set by reverse proxies to pass original client information. It's crucial to only apply this middleware if truly behind a proxy and to correctly specify the number of proxies setting each header to avoid security vulnerabilities. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/proxy_fix.rst#_snippet_0 LANGUAGE: python CODE: ``` from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix( app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 ) ``` ---------------------------------------- TITLE: Bind uWSGI to all external IPs DESCRIPTION: This snippet explains how to configure uWSGI to bind to all external IP addresses (`0.0.0.0`) on a non-privileged port. It includes a crucial security warning against using this setup when a reverse proxy is already in place. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/uwsgi.rst#_snippet_4 LANGUAGE: text CODE: ``` $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app ``` ---------------------------------------- TITLE: Flask File Upload Application Initialization DESCRIPTION: This code initializes a Flask application for file uploads. It imports necessary modules like os, Flask, request, and secure_filename. It defines the UPLOAD_FOLDER path and ALLOWED_EXTENSIONS set, then configures the Flask app with the upload folder. This setup is crucial for handling file uploads securely and efficiently. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_0 LANGUAGE: Python CODE: ``` import os from flask import Flask, flash, request, redirect, url_for from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/path/to/the/uploads' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER ``` ---------------------------------------- TITLE: Flask File Validation and Upload Route DESCRIPTION: This snippet defines the allowed_file function to validate file extensions and the main upload_file Flask route. The route handles both GET requests (displaying the upload form) and POST requests (processing file uploads). It checks for file presence, validates the filename, secures it using secure_filename, saves the file, and redirects the user to a download URL. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_1 LANGUAGE: Python CODE: ``` def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('download_file', name=filename)) return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form method=post enctype=multipart/form-data> <input type=file name=file> <input type=submit value=Upload> </form> ''' ``` ---------------------------------------- TITLE: Flask send_from_directory Function DESCRIPTION: Documentation for the flask.send_from_directory function, used to safely serve files from a specified directory. This function is essential for creating download endpoints while mitigating security risks by ensuring only files within the designated directory are accessible. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_7 LANGUAGE: APIDOC CODE: ``` flask.send_from_directory(directory: str, path: str, **options) -> flask.Response directory: str - The directory from which to send the file. path: str - The filename or path relative to the directory to send. options: dict - Additional options for sending the file (e.g., as_attachment=True, mimetype='image/png'). Returns: flask.Response - A response object that serves the file. Description: Sends a file from a given directory, ensuring security by preventing access to files outside the specified directory. ``` ---------------------------------------- TITLE: Disabling Autoescaping in Jinja2 Templates DESCRIPTION: This code snippet shows how to temporarily disable autoescaping within a Jinja2 template using the '{% autoescape %}' block. This is useful when you need to explicitly inject unescaped HTML, for example, from a trusted source like a markdown converter. Caution is advised when using this feature due to potential security risks. SOURCE: https://github.com/pallets/flask/blob/main/docs/templating.rst#_snippet_2 LANGUAGE: HTML+Jinja CODE: ``` {% autoescape false %} <p>autoescaping is disabled here <p>{{ will_not_be_escaped }} {% endautoescape %} ``` ---------------------------------------- TITLE: Make Flask Server Externally Visible DESCRIPTION: By default, the Flask development server is only accessible from the local machine. This command demonstrates how to make the server publicly available on the network by adding '--host=0.0.0.0'. This tells the operating system to listen on all public IP addresses, but should only be used if the debugger is disabled or users on the network are trusted due to security risks. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_2 LANGUAGE: text CODE: ``` $ flask run --host=0.0.0.0 ``` ---------------------------------------- TITLE: Execute Raw SQL Statement with SQLAlchemy Engine DESCRIPTION: This example demonstrates how to execute a raw SQL string directly using the SQLAlchemy engine's `execute` method. It supports parameterized queries for security and flexibility, allowing direct interaction with the database when ORM is not preferred. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/sqlalchemy.rst#_snippet_14 LANGUAGE: Python CODE: ``` engine.execute('select * from users where id = :1', [1]).first() ``` ---------------------------------------- TITLE: Run Flask Development Server in Debug Mode (CLI) DESCRIPTION: This command-line snippet demonstrates how to start the Flask development server with debug mode enabled, which activates the built-in Werkzeug debugger. This setup is intended for development environments only due to security implications. SOURCE: https://github.com/pallets/flask/blob/main/docs/debugging.rst#_snippet_0 LANGUAGE: text CODE: ``` $ flask --app hello run --debug ``` ---------------------------------------- TITLE: Test Blog Post Access Control in Flask with Pytest DESCRIPTION: This set of tests validates access control for blog post management. `test_login_required` ensures unauthenticated users are redirected to the login page for create, update, and delete actions. `test_author_required` verifies that only the post's author can modify or delete it, returning a 403 Forbidden status otherwise. `test_exists_required` checks that a 404 Not Found status is returned if an attempt is made to access or modify a non-existent post. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_16 LANGUAGE: python CODE: ``` @pytest.mark.parametrize('path', ( '/create', '/1/update', '/1/delete', )) def test_login_required(client, path): response = client.post(path) assert response.headers["Location"] == "/auth/login" def test_author_required(app, client, auth): # change the post author to another user with app.app_context(): db = get_db() db.execute('UPDATE post SET author_id = 2 WHERE id = 1') db.commit() auth.login() # current user can't modify other user's post assert client.post('/1/update').status_code == 403 assert client.post('/1/delete').status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in client.get('/').data @pytest.mark.parametrize('path', ( '/2/update', '/2/delete', )) def test_exists_required(client, auth, path): auth.login() assert client.post(path).status_code == 404 ``` ---------------------------------------- TITLE: Flask Decorator for Requiring User Authentication DESCRIPTION: This Python decorator, 'login_required', is designed to protect Flask views by ensuring that a user is logged in before accessing them. It wraps the original view function, checks if 'g.user' is 'None' (indicating no logged-in user), and if so, redirects to the login page. Otherwise, it proceeds to execute the original view function, passing along any keyword arguments. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_6 LANGUAGE: python CODE: ``` def login_required(view): @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for('auth.login')) return view(**kwargs) return wrapped_view ``` ---------------------------------------- TITLE: Werkzeug secure_filename Function Usage Example DESCRIPTION: This example demonstrates the usage and output of the werkzeug.utils.secure_filename function in a Python REPL. It illustrates how a potentially malicious filename containing directory traversal attempts (../../..) is sanitized into a safe filename, effectively preventing path manipulation vulnerabilities when storing user-provided file names. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_2 LANGUAGE: Python CODE: ``` >>> secure_filename('../../../../home/username/.bashrc') 'home_username_.bashrc' ``` ---------------------------------------- TITLE: Enable Debug Mode for Flask Application DESCRIPTION: This command shows how to run the Flask application in debug mode using the '--debug' option. Debug mode automatically reloads the server on code changes and provides an interactive debugger in the browser for errors. It also displays a debugger PIN. Debug mode should never be used in a production environment due to security vulnerabilities. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_3 LANGUAGE: text CODE: ``` $ flask --app hello run --debug * Serving Flask app 'hello' * Debug mode: on * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: nnn-nnn-nnn ``` ---------------------------------------- TITLE: Test User Logout in Flask with Pytest DESCRIPTION: Tests the Flask logout view. This snippet ensures that after a user logs out, their `user_id` is successfully removed from the session, confirming the logout operation's effectiveness. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_14 LANGUAGE: python CODE: ``` def test_logout(client, auth): auth.login() with client: auth.logout() assert 'user_id' not in session ``` ---------------------------------------- TITLE: Test User Login and Input Validation in Flask with Pytest DESCRIPTION: Tests the Flask login view. `test_login` verifies successful user login, redirection to the home page, and correct `session` and `g` context updates. `test_login_validate_input` utilizes `pytest.mark.parametrize` to efficiently test various invalid username/password combinations, asserting that the expected error messages are present in the response data. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_13 LANGUAGE: python CODE: ``` def test_login(client, auth): assert client.get('/auth/login').status_code == 200 response = auth.login() assert response.headers["Location"] == "/" with client: client.get('/') assert session['user_id'] == 1 assert g.user['username'] == 'test' @pytest.mark.parametrize(('username', 'password', 'message'), ( ('a', 'test', b'Incorrect username.'), ('test', 'a', b'Incorrect password.'), )) def test_login_validate_input(auth, username, password, message): response = auth.login(username, password) assert message in response.data ``` ---------------------------------------- TITLE: Flask User Login View Implementation DESCRIPTION: This Python code defines the '/login' route for a Flask application, handling both GET and POST requests. On POST, it retrieves username and password, queries the database for the user, verifies the password hash using 'check_password_hash', and manages the user session upon successful login. It also handles incorrect credentials and redirects to the index page. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_3 LANGUAGE: python CODE: ``` @bp.route('/login', methods=('GET', 'POST')) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('index')) flash(error) return render_template('auth/login.html') ``` ---------------------------------------- TITLE: Define Flask Authentication Helper Class and Pytest Fixture DESCRIPTION: Defines an `AuthActions` class to encapsulate common authentication operations like login and logout using a Flask test client. A Pytest fixture `auth` is provided to easily access these actions in tests, simplifying authentication setup. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_10 LANGUAGE: python CODE: ``` class AuthActions(object): def __init__(self, client): self._client = client def login(self, username='test', password='test'): return self._client.post( '/auth/login', data={'username': username, 'password': password} ) def logout(self): return self._client.get('/auth/logout') @pytest.fixture def auth(client): return AuthActions(client) ``` ---------------------------------------- TITLE: Manually Escape HTML in Flask Responses DESCRIPTION: When returning raw HTML from Flask, it's crucial to escape any user-provided input to prevent injection attacks. This Python snippet demonstrates using 'markupsafe.escape' to sanitize input from a URL parameter before rendering it in the HTML response. While Jinja templates handle this automatically, manual escaping is necessary when directly embedding untrusted data. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_4 LANGUAGE: python CODE: ``` from markupsafe import escape @app.route("/<name>") def hello(name): return f"Hello, {escape(name)}!" ``` ---------------------------------------- TITLE: Python SHA1 Checksum Stream Wrapper DESCRIPTION: This Python code defines a `ChecksumCalcStream` class that wraps an input stream to calculate its SHA1 checksum as data is read. It includes `read` and `readline` methods to update the hash. The `generate_checksum` function demonstrates how to replace the WSGI input stream with this custom stream and retrieve the hash object. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/requestchecksum.rst#_snippet_0 LANGUAGE: python CODE: ``` import hashlib class ChecksumCalcStream(object): def __init__(self, stream): self._stream = stream self._hash = hashlib.sha1() def read(self, bytes): rv = self._stream.read(bytes) self._hash.update(rv) return rv def readline(self, size_hint): rv = self._stream.readline(size_hint) self._hash.update(rv) return rv def generate_checksum(request): env = request.environ stream = ChecksumCalcStream(env['wsgi.input']) env['wsgi.input'] = stream return stream._hash ``` ---------------------------------------- TITLE: Load Logged-in User Before Each Flask Request DESCRIPTION: This Flask 'before_app_request' function ensures that user information is loaded and available for every request if a user is logged in. It retrieves the 'user_id' from the session, queries the database for the corresponding user, and stores the user object in 'g.user' for the duration of the request. If no user is logged in or the ID is invalid, 'g.user' is set to 'None'. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_4 LANGUAGE: python CODE: ``` @bp.before_app_request def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute( 'SELECT * FROM user WHERE id = ?', (user_id,) ).fetchone() ``` ---------------------------------------- TITLE: Handle Exceptions with Flask got_request_exception Signal DESCRIPTION: Shows how to use the `got_request_exception` signal to log or handle unhandled exceptions during request processing. It demonstrates filtering for specific exception types like `SecurityException`. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_23 LANGUAGE: python CODE: ``` from flask import got_request_exception def log_security_exception(sender, exception, **extra): if not isinstance(exception, SecurityException): return security_logger.exception( f"SecurityException at {request.url!r}", exc_info=exception, ) got_request_exception.connect(log_security_exception, app) ``` ---------------------------------------- TITLE: Flask Route Example for Request Checksum DESCRIPTION: This Flask example shows how to integrate the `generate_checksum` function into a route. It illustrates that accessing request data like `request.files` will consume the input stream, allowing the checksum to be fully calculated. The final checksum can then be retrieved using `hexdigest()`. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/requestchecksum.rst#_snippet_1 LANGUAGE: python CODE: ``` @app.route('/special-api', methods=['POST']) def special_api(): hash = generate_checksum(request) # Accessing this parses the input stream files = request.files # At this point the hash is fully constructed. checksum = hash.hexdigest() return f"Hash was: {checksum}" ``` ---------------------------------------- TITLE: Implement Login Required Decorator in Flask DESCRIPTION: This decorator ensures that a user is logged in before accessing a view function. If the user is not logged in, they are redirected to the 'login' page, passing the current URL as 'next'. It uses `functools.wraps` to preserve original function metadata. It assumes `g.user` stores the current user and 'login' is the login page endpoint. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/viewdecorators.rst#_snippet_0 LANGUAGE: python CODE: ``` from functools import wraps from flask import g, request, redirect, url_for def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if g.user is None: return redirect(url_for('login', next=request.url)) return f(*args, **kwargs) return decorated_function ``` ---------------------------------------- TITLE: Test Blog Index View in Flask with Pytest DESCRIPTION: Tests the blog index page's display logic. It verifies that the page correctly shows 'Log In' and 'Register' links when unauthenticated, and 'Log Out' when authenticated. Additionally, it asserts that post data (title, author, body, and an edit link for the author) is properly rendered. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_15 LANGUAGE: python CODE: ``` import pytest from flaskr.db import get_db def test_index(client, auth): response = client.get('/') assert b"Log In" in response.data assert b"Register" in response.data auth.login() response = client.get('/') assert b'Log Out' in response.data assert b'test title' in response.data assert b'by test on 2018-01-01' in response.data assert b'test\nbody' in response.data assert b'href="/1/update"' in response.data ``` ---------------------------------------- TITLE: Implement Path-based Application Dispatcher (Partial) DESCRIPTION: Introduces the concept of dispatching applications based on URL path segments, similar to subdomain dispatching. This snippet provides the initial setup for such a dispatcher, indicating it would look at the request path instead of the host header. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_4 LANGUAGE: python CODE: ``` from threading import Lock ``` ---------------------------------------- TITLE: Flask User Logout Functionality DESCRIPTION: This Python function defines the '/logout' route in Flask. It clears the user's session data, effectively logging them out. After clearing the session, it redirects the user to the application's index page, ensuring that subsequent requests will not have a logged-in user. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_5 LANGUAGE: python CODE: ``` @bp.route('/logout') def logout(): session.clear() return redirect(url_for('index')) ``` ---------------------------------------- TITLE: Test Flask Database Connection and Closure DESCRIPTION: Verifies that `get_db` returns the same database connection within an application context and that the connection is properly closed after the context exits, preventing further database operations. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_8 LANGUAGE: python CODE: ``` import sqlite3 import pytest from flaskr.db import get_db def test_get_close_db(app): with app.app_context(): db = get_db() assert db is get_db() with pytest.raises(sqlite3.ProgrammingError) as e: db.execute('SELECT 1') assert 'closed' in str(e.value) ``` ---------------------------------------- TITLE: Generate Flask Secret Key (Shell Command) DESCRIPTION: Provides a shell command using Python's `secrets` module to quickly generate a strong, random hexadecimal string suitable for use as a Flask secret key. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_30 LANGUAGE: shell CODE: ``` python -c 'import secrets; print(secrets.token_hex())' ``` ---------------------------------------- TITLE: Flaskr Jinja2 Base Template with User Authentication and Messages DESCRIPTION: This Jinja2 template defines the core structure for Flaskr web pages. It includes conditional rendering for user login status (displaying username, logout, register, or login links) and iterates through `get_flashed_messages()` to show system notifications. It also sets up extensible blocks for `title`, `header`, and `content`. SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/flaskr/templates/base.html#_snippet_0 LANGUAGE: Jinja2 CODE: ``` {% block title %}{% endblock %} - Flaskr [Flaskr]({{ url_for\('index'\) }}) ================================== {% if g.user %}* {{ g.user\['username'\] }} * [Log Out]({{ url_for\('auth.logout'\) }}) {% else %} * [Register]({{ url_for\('auth.register'\) }}) * [Log In]({{ url_for\('auth.login'\) }}) {% endif %} {% block header %}{% endblock %} {% for message in get\_flashed\_messages() %} {{ message }} {% endfor %} {% block content %}{% endblock %} ``` ---------------------------------------- TITLE: Test Flask Post Deletion DESCRIPTION: This Python test verifies the deletion of a blog post. It logs in, sends a POST request to the delete endpoint for post ID 1, asserts that the response redirects to the index URL, and then confirms the post is no longer present in the database. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_20 LANGUAGE: python CODE: ``` def test_delete(client, auth, app): auth.login() response = client.post('/1/delete') assert response.headers["Location"] == "/" with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post is None ``` ---------------------------------------- TITLE: Implement Subdomain-based Application Dispatcher DESCRIPTION: Defines a WSGI application class, `SubdomainDispatcher`, that dynamically creates and manages Flask application instances based on the request's subdomain. It uses a lock for thread-safe instance management and ensures that applications are created only once per subdomain. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_2 LANGUAGE: python CODE: ``` from threading import Lock class SubdomainDispatcher: def __init__(self, domain, create_app): self.domain = domain self.create_app = create_app self.lock = Lock() self.instances = {} def get_application(self, host): host = host.split(':')[0] assert host.endswith(self.domain), 'Configuration error' subdomain = host[:-len(self.domain)].rstrip('.') with self.lock: app = self.instances.get(subdomain) if app is None: app = self.create_app(subdomain) self.instances[subdomain] = app return app def __call__(self, environ, start_response): app = self.get_application(environ['HTTP_HOST']) return app(environ, start_response) ``` ---------------------------------------- TITLE: Create Context Local Proxy with Werkzeug LocalProxy DESCRIPTION: This snippet demonstrates using `werkzeug.local.LocalProxy` to create a context-local proxy for a resource, such as a database connection. Accessing the `db` proxy internally calls `get_db()`, providing a convenient way to access context-bound resources similar to `current_app`. SOURCE: https://github.com/pallets/flask/blob/main/docs/appcontext.rst#_snippet_3 LANGUAGE: python CODE: ``` from werkzeug.local import LocalProxy db = LocalProxy(get_db) ``` ---------------------------------------- TITLE: Verify Installed Python Packages with pip list DESCRIPTION: The `pip list` command displays all installed Python packages and their versions, including the location for editable installations. This helps confirm that the project has been successfully installed in the virtual environment and shows its current path. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/install.rst#_snippet_2 LANGUAGE: none CODE: ``` $ pip list Package Version Location -------------- --------- ---------------------------------- click 6.7 Flask 1.0 flaskr 1.0.0 /home/user/Projects/flask-tutorial itsdangerous 0.24 Jinja2 2.10 MarkupSafe 1.0 pip 9.0.3 Werkzeug 0.14.1 ``` ---------------------------------------- TITLE: Basic Flask Application with Message Flashing DESCRIPTION: This Python code demonstrates a complete Flask application setup for message flashing. It includes routes for the index and a login page, handling POST requests to validate credentials, flashing success messages, and redirecting users. A secret key is set for session management. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_0 LANGUAGE: Python CODE: ``` from flask import Flask, flash, redirect, render_template, \ request, url_for app = Flask(__name__) app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or \ request.form['password'] != 'secret': error = 'Invalid credentials' else: flash('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error=error) ``` ---------------------------------------- TITLE: Handling Subdomains with Nested Blueprints DESCRIPTION: Illustrates how subdomains are handled when nesting blueprints, where the child's subdomain prefixes the parent's in the final URL. SOURCE: https://github.com/pallets/flask/blob/main/docs/blueprints.rst#_snippet_7 LANGUAGE: python CODE: ``` parent = Blueprint('parent', __name__, subdomain='parent') child = Blueprint('child', __name__, subdomain='child') parent.register_blueprint(child) app.register_blueprint(parent) url_for('parent.child.create', _external=True) "child.parent.domain.tld" ``` ---------------------------------------- TITLE: Install uwsgi with compiler or from sdist DESCRIPTION: This snippet shows alternative `pip install` commands for `uwsgi` or `pyuwsgi` from source distribution. These methods require a compiler but provide SSL support, offering more robust deployment options. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/uwsgi.rst#_snippet_1 LANGUAGE: text CODE: ``` $ pip install uwsgi # or $ pip install --no-binary pyuwsgi pyuwsgi ``` ---------------------------------------- TITLE: Define Flask Authentication Blueprint (Python) DESCRIPTION: This Python code initializes a Flask Blueprint named 'auth' in `flaskr/auth.py`. It imports essential Flask modules and sets a URL prefix '/auth'. This blueprint serves as an organizational unit for authentication-related views and functions. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_0 LANGUAGE: python CODE: ``` import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) from werkzeug.security import check_password_hash, generate_password_hash from flaskr.db import get_db bp = Blueprint('auth', __name__, url_prefix='/auth') ``` ---------------------------------------- TITLE: Handling Login with Request Method and Form Data DESCRIPTION: Provides a comprehensive example of a login route that uses `request.method` to differentiate between GET and POST requests and `request.form` to access submitted username and password data. It includes basic validation and error handling. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_18 LANGUAGE: python CODE: ``` @app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error) ``` ---------------------------------------- TITLE: Test Flask Post Update Functionality DESCRIPTION: This Python test snippet verifies the update functionality for a blog post. It asserts that a GET request to the update page returns a 200 status, then posts data to update a post, and finally checks the database to confirm the post's title has been successfully updated. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_18 LANGUAGE: python CODE: ``` assert client.get('/1/update').status_code == 200 client.post('/1/update', data={'title': 'updated', 'body': ''}) with app.app_context(): db = get_db() post = db.execute('SELECT * FROM post WHERE id = 1').fetchone() assert post['title'] == 'updated' ``` ---------------------------------------- TITLE: Flask Session Management Example DESCRIPTION: Demonstrates how to use Flask sessions to store user-specific information across requests, including setting a secret key, handling login, and logout functionality. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_29 LANGUAGE: python CODE: ``` from flask import session # Set the secret key to some random bytes. Keep this really secret! app.secret_key = b'_5#y2L\"F4Q8z\n\xec]/' @app.route('/') def index(): if 'username' in session: return f'Logged in as {session["username"]}' return 'You are not logged in' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', None) return redirect(url_for('index')) ``` ---------------------------------------- TITLE: Flask Proxy Object Behavior and Access DESCRIPTION: Explains the nature of Flask's proxy objects, their limitations (e.g., type checking), and how to access the underlying proxied object using `_get_current_object`. SOURCE: https://github.com/pallets/flask/blob/main/docs/reqcontext.rst#_snippet_5 LANGUAGE: APIDOC CODE: ``` Flask Proxy Objects: Description: - Objects provided by Flask are proxies to other objects. - Accessed uniformly per worker thread, but point to unique underlying objects. Considerations: - Type Checks: Proxy objects cannot fake their type. Perform instance checks on the object being proxied. - Underlying Reference: Needed for sending signals or passing data to background threads. Accessing Underlying Object: - Method: werkzeug.local.LocalProxy._get_current_object() - Usage: app = current_app._get_current_object() - Example: my_signal.send(app) ``` ---------------------------------------- TITLE: Jinja Template for Index Page (index.html) DESCRIPTION: This Jinja template (`index.html`) extends `layout.html` and provides a simple overview page. It includes a link to the login page, demonstrating how child templates can inherit from a base layout that handles message flashing. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_2 LANGUAGE: HTML+Jinja CODE: ``` {% extends "layout.html" %} {% block body %} <h1>Overview</h1> <p>Do you want to <a href="{{ url_for('login') }}">log in?</a> {% endblock %} ``` ---------------------------------------- TITLE: Logging User Actions in a Flask Route DESCRIPTION: Demonstrates how to use `app.logger` within a Flask route to log user login attempts, both successful and failed, providing context about the user and the outcome of the authentication process. SOURCE: https://github.com/pallets/flask/blob/main/docs/logging.rst#_snippet_0 LANGUAGE: python CODE: ``` @app.route('/login', methods=['POST']) def login(): user = get_user(request.form['username']) if user.check_password(request.form['password']): login_user(user) app.logger.info('%s logged in successfully', user.username) return redirect(url_for('index')) else: app.logger.info('%s failed to log in', user.username) abort(401) ``` ---------------------------------------- TITLE: Install Test Dependencies and Run Tests with Coverage DESCRIPTION: This snippet outlines the steps to install testing dependencies, run tests using pytest, and generate a code coverage report. It ensures the project's functionality and code quality are verified. SOURCE: https://github.com/pallets/flask/blob/main/examples/javascript/README.rst#_snippet_2 LANGUAGE: text CODE: ``` $ pip install -e '.[test]' $ coverage run -m pytest $ coverage report ``` ---------------------------------------- TITLE: Manage Database Connection with Flask g Object and Teardown DESCRIPTION: This example shows how to manage a database connection using Flask's `g` object. The `get_db` function ensures a single connection per application context, while `teardown_db` is registered with `@app.teardown_appcontext` to automatically close the connection when the context ends, ensuring proper resource cleanup. SOURCE: https://github.com/pallets/flask/blob/main/docs/appcontext.rst#_snippet_2 LANGUAGE: python CODE: ``` from flask import g def get_db(): if 'db' not in g: g.db = connect_to_database() return g.db @app.teardown_appcontext def teardown_db(exception): db = g.pop('db', None) if db is not None: db.close() ``` ---------------------------------------- TITLE: Flask Session Interface Classes API Reference DESCRIPTION: Documents the classes that provide a way to replace Flask's session implementation, including `SessionInterface`, `SecureCookieSessionInterface`, `SecureCookieSession`, `NullSession`, and `SessionMixin`. Notes that `PERMANENT_SESSION_LIFETIME` can be an integer or `timedelta`. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_5 LANGUAGE: APIDOC CODE: ``` SessionInterface: Type: Class Description: Provides a simple way to replace the session implementation. Members: All members are documented. SecureCookieSessionInterface: Type: Class Description: Secure cookie-based session interface. Members: All members are documented. SecureCookieSession: Type: Class Description: Secure cookie session object. Members: All members are documented. NullSession: Type: Class Description: A session implementation that does nothing. Members: All members are documented. SessionMixin: Type: Class Description: Mixin for session objects. Members: All members are documented. Notice: The PERMANENT_SESSION_LIFETIME config can be an integer or timedelta. The Flask.permanent_session_lifetime attribute is always a timedelta. ``` ---------------------------------------- TITLE: Jinja Template for Login Page (login.html) DESCRIPTION: This Jinja template (`login.html`) extends `layout.html` and provides a login form. It displays any `error` message passed from the Flask view and includes input fields for username and password, demonstrating form submission within the flashing context. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_3 LANGUAGE: HTML+Jinja CODE: ``` {% extends "layout.html" %} {% block body %} <h1>Login</h1> {% if error %} <p class=error><strong>Error:</strong> {{ error }} {% endif %} <form method=post> <dl> <dt>Username: <dd><input type=text name=username value="{{ request.form.username }}"> <dt>Password: <dd><input type=password name=password> </dl> <p><input type=submit value=Login> </form> {% endblock %} ``` ---------------------------------------- TITLE: Embed Server-Side Data in JavaScript using Jinja tojson Filter DESCRIPTION: This Jinja template snippet shows how to safely embed server-side data (e.g., `chart_data`) directly into a JavaScript block. The `tojson` filter is crucial for converting the data into a valid JavaScript object and escaping unsafe HTML characters, preventing `SyntaxError` in the browser. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/javascript.rst#_snippet_1 LANGUAGE: jinja CODE: ``` <script> const chart_data = {{ chart_data|tojson }} chartLib.makeChart(chart_data) </script> ``` ---------------------------------------- TITLE: Handle Redirects in JavaScript Fetch Responses DESCRIPTION: This JavaScript example shows how to programmatically handle redirects after a `fetch` request. It checks the `response.redirected` property and, if true, manually updates `window.location` to the new URL provided by `response.url`, effectively changing the page after a server-side redirect. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/javascript.rst#_snippet_8 LANGUAGE: javascript CODE: ``` fetch("/login", {"body": ...}).then( response => { if (response.redirected) { window.location = response.url } else { showLoginError() } } ) ``` ---------------------------------------- TITLE: Clean Up with Flask appcontext_tearing_down Signal DESCRIPTION: Demonstrates how to use the `appcontext_tearing_down` signal for application context cleanup. This signal is always called, even on exceptions, and can be used for tasks like closing database sessions. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_27 LANGUAGE: python CODE: ``` def close_db_connection(sender, **extra): session.close() from flask import appcontext_tearing_down appcontext_tearing_down.connect(close_db_connection, app) ``` ---------------------------------------- TITLE: Install Testing Dependencies for Flask DESCRIPTION: Instructions to install the `pytest` and `coverage` libraries using pip, which are essential for writing and measuring unit tests in Flask applications. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_0 LANGUAGE: none CODE: ``` $ pip install pytest coverage ``` ---------------------------------------- TITLE: Flask: Helper Function to Get Blog Post by ID DESCRIPTION: This Python function retrieves a blog post from the database by its ID. It includes error handling to abort with a 404 status if the post doesn't exist and a 403 status if `check_author` is true and the logged-in user is not the post's author. This function is designed to be reusable across update and delete views. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/blog.rst#_snippet_7 LANGUAGE: python CODE: ``` def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone() if post is None: abort(404, f"Post id {id} doesn't exist.") if check_author and post['author_id'] != g.user['id']: abort(403) return post ``` ---------------------------------------- TITLE: Setting Nested Config via Environment Variable (Shell) DESCRIPTION: Demonstrates how to set a nested configuration value using environment variables with double underscores as separators, specifically for a Flask application. SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_18 LANGUAGE: text CODE: ``` $ export FLASK_MYAPI__credentials__username=user123 ``` ---------------------------------------- TITLE: Jinja2 Login Page Template Structure DESCRIPTION: This snippet illustrates the fundamental structure of a Jinja2 template for a login page. It extends a 'base.html' template and defines 'header' and 'content' blocks, including a title and placeholders for username and password fields. SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/flaskr/templates/auth/login.html#_snippet_0 LANGUAGE: Jinja2 CODE: ``` {% extends 'base.html' %} {% block header %} {% block title %}Log In{% endblock %} ===================================== {% endblock %} {% block content %} Username Password {% endblock %} ``` ---------------------------------------- TITLE: Combine Flask Applications with DispatcherMiddleware DESCRIPTION: Shows how to use Werkzeug's DispatcherMiddleware to combine multiple Flask applications (or any WSGI apps) under different URL prefixes, such as a frontend app on '/' and a backend app on '/backend'. This allows entirely separated applications to work next to each other in the same Python interpreter process. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_1 LANGUAGE: python CODE: ``` from werkzeug.middleware.dispatcher import DispatcherMiddleware from frontend_app import application as frontend from backend_app import application as backend application = DispatcherMiddleware(frontend, { '/backend': backend }) ``` ---------------------------------------- TITLE: Fetching Single Result with query_db DESCRIPTION: Example of using the `query_db` function to fetch a single row based on a condition, demonstrating safe parameter passing using question marks to prevent SQL injection. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/sqlite3.rst#_snippet_8 LANGUAGE: Python CODE: ``` user = query_db('select * from users where username = ?', [the_username], one=True) if user is None: print('No such user') else: print(the_username, 'has the id', user['user_id']) ``` ---------------------------------------- TITLE: Flask: Handling 400 Bad Request and 404 Not Found with abort DESCRIPTION: This Python snippet demonstrates how to use `flask.abort` within a route to signal HTTP errors. It aborts with a 400 Bad Request if a required username is missing from query arguments, and a 404 Not Found if the provided username does not correspond to an existing user. SOURCE: https://github.com/pallets/flask/blob/main/docs/errorhandling.rst#_snippet_7 LANGUAGE: python CODE: ``` from flask import abort, render_template, request # a username needs to be supplied in the query args # a successful request would be like /profile?username=jack @app.route("/profile") def user_profile(): username = request.arg.get("username") # if a username isn't supplied in the request, return a 400 bad request if username is None: abort(400) user = get_user(username=username) # if a user can't be found by their username, return 404 not found if user is None: abort(404) return render_template("profile.html", user=user) ``` ---------------------------------------- TITLE: Flask Session Object API Reference and Usage DESCRIPTION: Documents the `session` object, which allows remembering information across requests using signed cookies. It behaves like a dictionary and tracks modifications. Requires `Flask.secret_key` to be set. Includes an example of explicitly marking a session as modified. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_4 LANGUAGE: APIDOC CODE: ``` session: Type: Global Proxy Object (dict-like) Description: Stores information across requests using a signed cookie. Requires Flask.secret_key. Attributes: new: bool - True if the session is new. modified: bool - True if the session object detected a modification. Be advised that modifications on mutable structures are not picked up automatically; set this attribute to True yourself. permanent: bool - If set to True, the session lives for Flask.permanent_session_lifetime seconds (default 31 days). If set to False (default), the session will be deleted when the user closes the browser. Notes: This is a proxy. See :ref:`notes-on-proxies` for more information. ``` LANGUAGE: python CODE: ``` # this change is not picked up because a mutable object (here # a list) is changed. session['objects'].append(42) # so mark it as modified yourself session.modified = True ``` ---------------------------------------- TITLE: Test Flask User Registration View and Input Validation DESCRIPTION: Tests the user registration view, verifying successful rendering on GET requests, redirection to login on valid POST data, and proper storage of user data in the database. It also includes parameterized tests for invalid input scenarios and expected error messages. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_11 LANGUAGE: python CODE: ``` import pytest from flask import g, session from flaskr.db import get_db def test_register(client, app): assert client.get('/auth/register').status_code == 200 response = client.post( '/auth/register', data={'username': 'a', 'password': 'a'} ) assert response.headers["Location"] == "/auth/login" with app.app_context(): assert get_db().execute( "SELECT * FROM user WHERE username = 'a'", ).fetchone() is not None @pytest.mark.parametrize(('username', 'password', 'message'), ( ('', '', b'Username is required.'), ('a', '', b'Password is required.'), ('test', 'test', b'already registered'), )) def test_register_validate_input(client, username, password, message): response = client.post( '/auth/register', data={'username': username, 'password': password} ) assert message in response.data ``` ---------------------------------------- TITLE: Clean Up with Flask request_tearing_down Signal DESCRIPTION: Provides an example of connecting to the `request_tearing_down` signal, which is always called when a request is tearing down, even if an exception occurred. Useful for resource cleanup like closing database connections. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_25 LANGUAGE: python CODE: ``` def close_db_connection(sender, **extra): session.close() from flask import request_tearing_down request_tearing_down.connect(close_db_connection, app) ``` ---------------------------------------- TITLE: Implement User Registration View Function in Flask (Python) DESCRIPTION: This Python code defines the `register` view for the Flask 'auth' blueprint, handling GET and POST requests. It validates user input, hashes passwords, and inserts new users into the database. Upon successful registration, it redirects to the login page; otherwise, it flashes an error message. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/views.rst#_snippet_2 LANGUAGE: python CODE: ``` @bp.route('/register', methods=('GET', 'POST')) def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' if error is None: try: db.execute( "INSERT INTO user (username, password) VALUES (?, ?)", (username, generate_password_hash(password)), ) db.commit() except db.IntegrityError: error = f"User {username} is already registered." else: return redirect(url_for("auth.login")) flash(error) return render_template('auth/register.html') ``` ---------------------------------------- TITLE: Pass Minimal Data to Celery Tasks (User ID Example) DESCRIPTION: This snippet illustrates the best practice for passing data to Celery tasks: pass only the minimal, serializable data required to re-fetch or recreate complex objects within the task itself. Instead of passing a non-serializable SQLAlchemy user object, the example passes only the `user_id`, allowing the task to query the database for the user object independently. This prevents serialization issues and ensures task robustness. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/celery.rst#_snippet_12 LANGUAGE: python CODE: ``` @shared_task def generate_user_archive(user_id: str) -> None: user = db.session.get(User, user_id) ... generate_user_archive.delay(current_user.id) ``` ---------------------------------------- TITLE: Git Ignore Configuration for Flask Project (.gitignore) DESCRIPTION: This `.gitignore` file snippet provides a list of common files and directories that should be ignored by Git in a Flask project. These typically include generated files, virtual environments, and build artifacts to keep the repository clean. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/layout.rst#_snippet_3 LANGUAGE: none CODE: ``` .venv/ *.pyc __pycache__/ instance/ .pytest_cache/ .coverage htmlcov/ dist/ build/ *.egg-info/ ``` ---------------------------------------- TITLE: APIDOC: Flask `TESTING` Configuration Flag DESCRIPTION: Documentation for the `TESTING` configuration flag in Flask. When set to `True`, it indicates that the application is running in test mode, which can alter internal Flask behavior and affect how extensions operate to facilitate testing. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_4 LANGUAGE: APIDOC CODE: ``` app.config['TESTING'] = True Description: A boolean flag that enables test mode for the Flask application. Effect: Modifies Flask's internal behavior and can be used by extensions to simplify testing. ``` ---------------------------------------- TITLE: Accessing Nested Config from Flask App (Python) DESCRIPTION: Shows how to access a nested configuration value within a Flask application's config object after it has been loaded from environment variables using the double underscore convention. SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_19 LANGUAGE: python CODE: ``` app.config["MYAPI"]["credentials"]["username"] # Is "user123" ``` ---------------------------------------- TITLE: Flask Core Application and Request Utilities API DESCRIPTION: This section documents various Flask functions related to request and application context, URL generation, response handling, and flow control. These functions are typically available within an active application or request context. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_10 LANGUAGE: APIDOC CODE: ``` has_request_context() copy_current_request_context() has_app_context() url_for() abort() redirect() make_response() after_this_request() send_file() send_from_directory() ``` ---------------------------------------- TITLE: Testing Flask Request Context with Manual Preprocessing DESCRIPTION: This Python snippet demonstrates how to use `app.test_request_context` to simulate a request for testing. It shows that `before_request` functions are not automatically called, and how `app.preprocess_request()` can be manually invoked to run these functions, allowing access to context-dependent variables like `g.user`. SOURCE: https://github.com/pallets/flask/blob/main/docs/testing.rst#_snippet_11 LANGUAGE: python CODE: ``` def test_auth_token(app): with app.test_request_context("/user/2/edit", headers={"X-Auth-Token": "1"}): app.preprocess_request() assert g.user.name == "Flask" ``` ---------------------------------------- TITLE: Jinja Template for Filtering Flashed Messages by Category DESCRIPTION: This Jinja template snippet demonstrates how to filter flashed messages by category using `category_filter`. It allows rendering specific message types (e.g., 'error' messages) in dedicated blocks, providing more granular control over their display and styling. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/flashing.rst#_snippet_6 LANGUAGE: HTML+Jinja CODE: ``` {% with errors = get_flashed_messages(category_filter=["error"]) %} {% if errors %} <div class="alert-message block-message error"> <a class="close" href="#">×</a> <ul> {%- for msg in errors %} <li>{{ msg }}</li> {% endfor -%} </ul> </div> {% endif %} {% endwith %} ``` ---------------------------------------- TITLE: Flask Class-based View Handling URL Variables DESCRIPTION: Shows a `DetailView` class designed to handle URL variables. The `id` captured from the URL is passed as a keyword argument to the `dispatch_request` method, allowing the view to fetch a specific item based on its ID. SOURCE: https://github.com/pallets/flask/blob/main/docs/views.rst#_snippet_4 LANGUAGE: python CODE: ``` class DetailView(View): def __init__(self, model): self.model = model self.template = f"{model.__name__.lower()}/detail.html" def dispatch_request(self, id): item = self.model.query.get_or_404(id) return render_template(self.template, item=item) app.add_url_rule( "/users/<int:id>", view_func=DetailView.as_view("user_detail", User) ) ``` ---------------------------------------- TITLE: Example Usage of PathDispatcher with Dynamic App Creation DESCRIPTION: Demonstrates how to instantiate `PathDispatcher` by providing a `default_app` and a `make_app` function. The `make_app` function dynamically creates an application based on a user retrieved from the path prefix, showcasing the dispatcher's ability to handle dynamic application instances. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_6 LANGUAGE: python CODE: ``` from myapplication import create_app, default_app, get_user_for_prefix def make_app(prefix): user = get_user_for_prefix(prefix) if user is not None: return create_app(user) application = PathDispatcher(default_app, make_app) ``` ---------------------------------------- TITLE: Flask Signal: appcontext_tearing_down DESCRIPTION: This signal is sent when the app context is tearing down. It is always called, even if an exception is caused. It also passes an `exc` keyword argument with a reference to the exception if one occurred. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_28 LANGUAGE: APIDOC CODE: ``` appcontext_tearing_down: Signal Sent when the application context is tearing down. Parameters: sender: The application instance. exc (optional): The exception that caused the teardown, if any. **extra: Additional keyword arguments. ``` ---------------------------------------- TITLE: Registering Database Functions with Flask App Context (Python) DESCRIPTION: This Python snippet demonstrates how to register database cleanup and command-line initialization functions (`close_db`, `init_db_command`) with a Flask application instance. It utilizes `app.teardown_appcontext` to ensure cleanup after responses and `app.cli.add_command` to make `init_db_command` available via the Flask CLI. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/database.rst#_snippet_3 LANGUAGE: python CODE: ``` def init_app(app): app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) ``` ---------------------------------------- TITLE: Temporarily Set User with Flask appcontext_pushed Signal DESCRIPTION: Illustrates using the `appcontext_pushed` signal with a context manager to temporarily set a user on the `g` object for testing purposes. This signal is sent when an application context is pushed. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_29 LANGUAGE: python CODE: ``` from contextlib import contextmanager from flask import appcontext_pushed @contextmanager def user_set(app, user): def handler(sender, **kwargs): g.user = user with appcontext_pushed.connected_to(handler, app): yield # And in the testcode: def test_user_me(self): with user_set(app, 'john'): c = app.test_client() resp = c.get('/users/me') assert resp.data == 'username=john' ``` ---------------------------------------- TITLE: Flask Signal: request_tearing_down DESCRIPTION: This signal is sent when the request is tearing down. It is always called, even if an exception is caused. As of Flask 0.9, it also passes an `exc` keyword argument with a reference to the exception if one occurred. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_26 LANGUAGE: APIDOC CODE: ``` request_tearing_down: Signal Sent when the request is tearing down. Parameters: sender: The application instance. exc (optional): The exception that caused the teardown, if any. **extra: Additional keyword arguments. ``` ---------------------------------------- TITLE: Embed Server-Side Data in HTML Data Attribute using Jinja tojson Filter DESCRIPTION: This Jinja template snippet illustrates an alternative method for passing server-side data to JavaScript by embedding it within an HTML `data-` attribute. It's important to use single quotes around the value when using the `tojson` filter in this context to ensure valid and safe HTML. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/javascript.rst#_snippet_2 LANGUAGE: jinja CODE: ``` <div data-chart='{{ chart_data|tojson }}'></div> ``` ---------------------------------------- TITLE: Flask Application with Combined URL Processors and Simplified Routes DESCRIPTION: Presents a complete Flask application demonstrating the combined use of `url_defaults` and `url_value_preprocessor` to handle language codes automatically, simplifying the view functions. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/urlprocessors.rst#_snippet_3 LANGUAGE: Python CODE: ``` from flask import Flask, g app = Flask(__name__) @app.url_defaults def add_language_code(endpoint, values): if 'lang_code' in values or not g.lang_code: return if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values['lang_code'] = g.lang_code @app.url_value_preprocessor def pull_lang_code(endpoint, values): g.lang_code = values.pop('lang_code', None) @app.route('/<lang_code>/') def index(): ... @app.route('/<lang_code>/about') def about(): ... ``` ---------------------------------------- TITLE: Flask Request Object and Global Proxy API Reference DESCRIPTION: Documents the Request object, which provides access to incoming request data, and the global 'request' proxy object. Flask parses incoming request data and ensures thread-safe access. Excludes the 'json_module' member. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_2 LANGUAGE: APIDOC CODE: ``` Request: Type: Class Description: Provides access to incoming request data. Members: All members and inherited members are documented, excluding 'json_module'. request: Type: Global Proxy Object (instance of flask.Request) Description: Used to access incoming request data. Flask parses data and ensures correct data for the active thread in multithreaded environments. Notes: This is a proxy. See :ref:`notes-on-proxies` for more information. ``` ---------------------------------------- TITLE: Example Usage of connected_to for Signal Subscription DESCRIPTION: This snippet shows how to use the `captured_templates` function (modified to utilize `connected_to`) to record template rendering. The `templates` list is passed directly to the function, and the `with` block ensures the subscription is active only for its duration, making it suitable for focused testing or auditing. SOURCE: https://github.com/pallets/flask/blob/main/docs/signals.rst#_snippet_3 LANGUAGE: Python CODE: ``` templates = [] with captured_templates(app, templates, **extra): ... template, context = templates[0] ``` ---------------------------------------- TITLE: Define WTForms Registration Form Class DESCRIPTION: This Python class defines a registration form using WTForms, specifying fields like username, email, password, and terms of service acceptance, along with validators for length, data presence, and password matching. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/wtforms.rst#_snippet_0 LANGUAGE: python CODE: ``` from wtforms import Form, BooleanField, StringField, PasswordField, validators class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password') accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()]) ``` ---------------------------------------- TITLE: Flask Endpoint for Serving Uploaded Files DESCRIPTION: This code defines a Flask route (/uploads/<name>) to serve uploaded files from the configured UPLOAD_FOLDER. It utilizes the flask.send_from_directory function to safely send files, which is crucial for preventing directory traversal attacks when users request files by name, ensuring only files within the designated upload directory are accessible. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/fileuploads.rst#_snippet_3 LANGUAGE: Python CODE: ``` from flask import send_from_directory @app.route('/uploads/<name>') def download_file(name): return send_from_directory(app.config["UPLOAD_FOLDER"], name) ``` ---------------------------------------- TITLE: Config Class with Dynamic Property (Python) DESCRIPTION: Illustrates how to use Python properties within configuration classes to define dynamic configuration values that depend on other settings within the class, such as constructing a database URI from a server address. SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_25 LANGUAGE: python CODE: ``` class Config(object): """Base config, uses staging database server.""" TESTING = False DB_SERVER = '192.168.1.56' @property def DATABASE_URI(self): # Note: all caps return f"mysql://user@{self.DB_SERVER}/foo" class ProductionConfig(Config): """Uses production database server.""" DB_SERVER = '192.168.19.32' class DevelopmentConfig(Config): ``` ---------------------------------------- TITLE: Example Usage of SubdomainDispatcher DESCRIPTION: Illustrates how to instantiate and use the `SubdomainDispatcher` with a `make_app` function. The `make_app` function dynamically creates a Flask application based on the subdomain's associated user or returns a 404 Not Found exception if no user is found. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_3 LANGUAGE: python CODE: ``` from myapplication import create_app, get_user_for_subdomain from werkzeug.exceptions import NotFound def make_app(subdomain): user = get_user_for_subdomain(subdomain) if user is None: # if there is no user for that subdomain we still have # to return a WSGI application that handles that request. # We can then just return the NotFound() exception as # application which will render a default 404 page. # You might also redirect the user to the main page then return NotFound() # otherwise create the application for the specific user return create_app(user) application = SubdomainDispatcher('example.com', make_app) ``` ---------------------------------------- TITLE: Flask Blog Post Deletion Endpoint (flaskr/blog.py) DESCRIPTION: This Python Flask snippet defines the `delete` view for a blog post. It handles POST requests to the `/<int:id>/delete` URL, ensures the user is logged in, retrieves the post to confirm its existence, deletes the corresponding entry from the 'post' table in the database, commits the transaction, and then redirects the user to the blog index page. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/blog.rst#_snippet_10 LANGUAGE: python CODE: ``` @bp.route('/<int:id>/delete', methods=('POST',)) @login_required def delete(id): get_post(id) db = get_db() db.execute('DELETE FROM post WHERE id = ?', (id,)) db.commit() return redirect(url_for('blog.index')) ``` ---------------------------------------- TITLE: Serving a Single-Page Application with a Flask API DESCRIPTION: This Flask application demonstrates how to serve a Single-Page Application (SPA) by configuring a static folder for frontend files and creating a catch-all route that serves the SPA's index.html. It also includes a simple '/heartbeat' API endpoint for health checks. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/singlepageapplications.rst#_snippet_0 LANGUAGE: Python CODE: ``` from flask import Flask, jsonify app = Flask(__name__, static_folder='app', static_url_path="/app") @app.route("/heartbeat") def heartbeat(): return jsonify({"status": "healthy"}) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return app.send_static_file("index.html") ``` ---------------------------------------- TITLE: Basic Flask Application Setup DESCRIPTION: Demonstrates a minimal Flask application that returns 'Hello World!' on the root path. This serves as a basic WSGI application that can be run with any WSGI server. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/appdispatch.rst#_snippet_0 LANGUAGE: python CODE: ``` from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' ``` ---------------------------------------- TITLE: Flask: Application-level 404 Handler for Blueprint URL Errors DESCRIPTION: This Python snippet highlights that 404/405 error handlers defined on blueprints are only triggered by explicit `raise` or `abort` calls within the blueprint's views. For invalid URLs not owned by a blueprint, the handler must be defined at the application level to catch all such errors. SOURCE: https://github.com/pallets/flask/blob/main/docs/errorhandling.rst#_snippet_15 LANGUAGE: python CODE: ``` from flask import jsonify, render_template # at the application level # not the blueprint level @app.errorhandler(404) ``` ---------------------------------------- TITLE: Test Blog Post Creation and Update in Flask with Pytest DESCRIPTION: Tests the functionality of creating and updating blog posts. `test_create` verifies that the create page renders correctly on a GET request and that a POST request with valid data successfully inserts a new post into the database. `test_update` (partially shown) would similarly test the modification of existing post data. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_17 LANGUAGE: python CODE: ``` def test_create(client, auth, app): auth.login() assert client.get('/create').status_code == 200 client.post('/create', data={'title': 'created', 'body': ''}) with app.app_context(): db = get_db() count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0] assert count == 2 def test_update(client, auth, app): auth.login() ``` ---------------------------------------- TITLE: Flask Signal: appcontext_popped DESCRIPTION: This signal is sent when an application context is popped. The sender is the application. This usually falls in line with the `appcontext_tearing_down` signal. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_31 LANGUAGE: APIDOC CODE: ``` appcontext_popped: Signal Sent when an application context is popped. Parameters: sender: The application instance. **kwargs: Additional keyword arguments. ``` ---------------------------------------- TITLE: Query MongoEngine Documents by Field Value DESCRIPTION: This snippet demonstrates basic querying in MongoEngine. It shows how to use the `objects` attribute of a document class to find documents based on exact field values, including the use of `get_or_404()` for retrieving a single document or raising an error if not found. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/mongoengine.rst#_snippet_5 LANGUAGE: python CODE: ``` bttf = Movie.objects(title="Back To The Future").get_or_404() ``` ---------------------------------------- TITLE: Flask Application Globals API Reference DESCRIPTION: Documents the `g` object, a special namespace for storing data valid for a single request within an application context, ensuring thread-safety. Also documents the `_AppCtxGlobals` class it defaults to. SOURCE: https://github.com/pallets/flask/blob/main/docs/api.rst#_snippet_8 LANGUAGE: APIDOC CODE: ``` g: Type: Global Proxy Object (instance of Flask.app_ctx_globals_class, defaults to ctx._AppCtxGlobals) Description: A namespace object that can store data during an application context. Ensures thread-safety for request-specific data. Usage Example: A `before_request` function could load a user object from a session id, then set `g.user` to be used in the view function. Version Changed: 0.10 (Bound to the application context instead of the request context). Notes: This is a proxy. See :ref:`notes-on-proxies` for more information. flask.ctx._AppCtxGlobals: Type: Class Description: Default class for application context globals. Members: All members are documented. ``` |