File size: 60,790 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 |
======================== CODE SNIPPETS ======================== 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: 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: Example Jinja2 HTML Template Structure DESCRIPTION: Provides a basic Jinja2 template demonstrating conditional rendering (`{% if %}` / `{% else %}`) and variable display (`{{ variable }}`). This template is designed to be rendered by a Flask application, showcasing how dynamic content can be integrated into standard HTML markup. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_13 LANGUAGE: html CODE: ``` <!doctype html> <title>Hello from Flask</title> {% if person %} <h1>Hello {{ person }}!</h1> {% else %} <h1>Hello, World!</h1> {% endif %} ``` ---------------------------------------- TITLE: Install Python Environment and Flask Project DESCRIPTION: This snippet provides commands to set up a Python virtual environment, activate it, and install the current Flask project in editable mode. This is a standard procedure for preparing a Python development environment. SOURCE: https://github.com/pallets/flask/blob/main/examples/javascript/README.rst#_snippet_0 LANGUAGE: text CODE: ``` $ python3 -m venv .venv $ . .venv/bin/activate $ pip install -e . ``` ---------------------------------------- TITLE: Example Flask Debug Server Console Output DESCRIPTION: This snippet displays the typical console output when the Flask development server starts in debug mode. It confirms the application being served, the active debug mode, the local URL for access, and the activation of the debugger with its PIN, indicating a successful server startup. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_4 LANGUAGE: text CODE: ``` * Serving Flask app "flaskr" * 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: 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: Handle Multiple HTTP Methods for Flask Routes DESCRIPTION: Shows how to configure a Flask route to respond to specific HTTP methods (e.g., GET, POST) using the `methods` argument in the `@app.route` decorator. This allows for different logic based on the request type, such as handling form submissions. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_9 LANGUAGE: python CODE: ``` from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() ``` ---------------------------------------- TITLE: Install Gunicorn and application in a virtual environment DESCRIPTION: This snippet outlines the standard procedure to set up a Python virtual environment, install your Flask application, and then install Gunicorn using pip. This is a common and recommended setup for deploying Python web applications. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_0 LANGUAGE: shell CODE: ``` $ cd hello-app $ python -m venv .venv $ . .venv/bin/activate $ pip install . # install your application $ pip install gunicorn ``` ---------------------------------------- TITLE: Flask Redirects and Errors: `redirect` and `abort` DESCRIPTION: Illustrates the basic usage of `flask.redirect` to send a user to another URL and `flask.abort` to immediately terminate a request with an HTTP error code. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_24 LANGUAGE: python CODE: ``` from flask import abort, redirect, url_for @app.route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): abort(401) this_is_never_executed() ``` ---------------------------------------- TITLE: Separate Flask Views for GET and POST Methods DESCRIPTION: Demonstrates how to define distinct view functions for different HTTP methods (GET and POST) on the same route in Flask. This approach, using `@app.get` and `@app.post` decorators, helps organize logic when specific actions are tied to particular request methods, such as displaying a form versus processing its submission. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_10 LANGUAGE: python CODE: ``` @app.get('/login') def login_get(): return show_the_login_form() @app.post('/login') def login_post(): return do_the_login() ``` ---------------------------------------- TITLE: Run a Flask Application from the Command Line DESCRIPTION: This command shows how to run the Flask application using the 'flask' command-line interface. The '--app hello' option specifies the application file (e.g., 'hello.py'). The output indicates the server is running locally, typically on port 5000. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_1 LANGUAGE: text CODE: ``` $ flask --app hello run * Serving Flask app 'hello' * Running on http://127.0.0.1:5000 (Press CTRL+C to quit) ``` ---------------------------------------- TITLE: Define Basic Flask Routes DESCRIPTION: Demonstrates how to bind Python functions to specific URL paths using the `@app.route` decorator in Flask. This allows the application to respond to requests at the defined endpoints. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_5 LANGUAGE: python CODE: ``` @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' ``` ---------------------------------------- TITLE: Run Flask Application DESCRIPTION: This command starts the Flask development server for the 'js_example' application. It makes the application accessible via a web browser at the specified local address. SOURCE: https://github.com/pallets/flask/blob/main/examples/javascript/README.rst#_snippet_1 LANGUAGE: text CODE: ``` $ flask --app js_example run ``` ---------------------------------------- TITLE: Flask Error Handling: Custom 404 Page DESCRIPTION: Shows how to customize error pages in Flask using the `errorhandler` decorator. This example specifically handles a 404 Not Found error by rendering a custom template and setting the correct status code. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_25 LANGUAGE: python CODE: ``` from flask import render_template @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 ``` ---------------------------------------- TITLE: Create a Minimal Flask Web Application DESCRIPTION: This snippet demonstrates how to create a basic Flask application. It imports the Flask class, creates an application instance, defines a route for the root URL ('/'), and returns a simple 'Hello, World!' HTML paragraph. The '__name__' argument helps Flask locate resources like templates. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_0 LANGUAGE: python CODE: ``` from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" ``` ---------------------------------------- TITLE: Install pyuwsgi for Flask applications DESCRIPTION: This snippet provides shell commands to set up a Python virtual environment, install a Flask application, and then install the `pyuwsgi` package, which offers precompiled wheels for quick setup but lacks SSL support. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/uwsgi.rst#_snippet_0 LANGUAGE: text CODE: ``` $ cd hello-app $ python -m venv .venv $ . .venv/bin/activate $ pip install . $ pip install pyuwsgi ``` ---------------------------------------- TITLE: Define Project Metadata with pyproject.toml DESCRIPTION: The `pyproject.toml` file is used to describe a Python project and define how it should be built. This example specifies the project's name, version, description, and runtime dependencies, along with the build system requirements for `flit_core`. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/install.rst#_snippet_0 LANGUAGE: toml CODE: ``` [project] name = "flaskr" version = "1.0.0" description = "The basic blog app built in the Flask tutorial." dependencies = [ "flask", ] [build-system] requires = ["flit_core<4"] build-backend = "flit_core.buildapi" ``` ---------------------------------------- TITLE: Importing the Flask Request Object DESCRIPTION: Shows the standard way to import the `request` object from the `flask` module, which is necessary before using it to access client data. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_17 LANGUAGE: python CODE: ``` from flask import request ``` ---------------------------------------- TITLE: Using request_context with WSGI Environment DESCRIPTION: Illustrates an alternative method for binding a request context by passing a full WSGI environment to `app.request_context`. This allows for more granular control over the request context during testing or specific scenarios. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_16 LANGUAGE: python CODE: ``` with app.request_context(environ): assert request.method == 'POST' ``` ---------------------------------------- TITLE: Running Flask App with Debug Mode - Shell DESCRIPTION: Command line example showing how to start a Flask development server with debug mode enabled using the `flask run` command. SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_3 LANGUAGE: text CODE: ``` $ flask --app hello run --debug ``` ---------------------------------------- TITLE: Basic Flask Application Setup and Configuration DESCRIPTION: This snippet demonstrates the initial setup of a Flask application by creating an instance of the Flask class. It shows how to configure the application using `app.config.from_mapping` for default settings and `app.config.from_prefixed_env()` for environment-based configuration. A basic route is also included to illustrate a simple 'Hello, World!' endpoint. SOURCE: https://github.com/pallets/flask/blob/main/docs/lifecycle.rst#_snippet_0 LANGUAGE: python CODE: ``` from flask import Flask app = Flask(__name__) app.config.from_mapping( SECRET_KEY="dev", ) app.config.from_prefixed_env() @app.route("/") def index(): return "Hello, World!" ``` ---------------------------------------- TITLE: Render Jinja2 Templates in Flask DESCRIPTION: Shows how to use Flask's `render_template` function to serve dynamic HTML pages. It demonstrates passing Python variables as keyword arguments to a Jinja2 template, enabling personalized content based on URL parameters or other application data. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_12 LANGUAGE: python CODE: ``` from flask import render_template @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', person=name) ``` ---------------------------------------- TITLE: Install Flaskr Test Dependencies DESCRIPTION: Command to install the testing dependencies required for running tests on the Flaskr application, specified in the project's setup. SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_5 LANGUAGE: bash CODE: ``` $ pip install '.[test]' ``` ---------------------------------------- TITLE: Flask File Upload: Basic Save DESCRIPTION: Demonstrates how to handle file uploads in Flask using `request.files` and save the uploaded file directly to the server's filesystem. It shows a basic POST request handler for file saving. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_20 LANGUAGE: python CODE: ``` from flask import request @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') ... ``` ---------------------------------------- TITLE: Flask API Endpoints Returning JSON (dict/list) DESCRIPTION: Illustrates how Flask automatically converts dictionaries or lists returned from view functions into JSON responses, simplifying the creation of API endpoints. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_28 LANGUAGE: python CODE: ``` @app.route("/me") def me_api(): user = get_current_user() return { "username": user.username, "theme": user.theme, "image": url_for("user_image", filename=user.image), } @app.route("/users") def users_api(): users = get_all_users() return [user.to_json() for user in users] ``` ---------------------------------------- TITLE: Install Flask from Source and Flaskr (Main Branch) DESCRIPTION: Instructions for installing Flask from its source directory and then Flaskr, specifically when working with the main development branch, ensuring all dependencies are met. SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_3 LANGUAGE: bash CODE: ``` $ pip install -e ../.. $ pip install -e . ``` ---------------------------------------- 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: Applying WSGI Middleware to Flask Applications DESCRIPTION: To integrate WSGI middleware, such as Werkzeug's `ProxyFix`, wrap the `app.wsgi_app` attribute. This approach ensures that the original `app` object remains accessible for direct configuration, while the middleware processes requests. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_32 LANGUAGE: python CODE: ``` from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) ``` ---------------------------------------- TITLE: Flask Cookies: Reading from Request DESCRIPTION: Shows how to read cookies sent by the client using `request.cookies.get()`. It emphasizes using `.get()` to avoid `KeyError` if the cookie is missing. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_22 LANGUAGE: python CODE: ``` from flask import request @app.route('/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing. ``` ---------------------------------------- TITLE: Build URLs in Flask using url_for Function DESCRIPTION: Demonstrates how to programmatically generate URLs for Flask functions using `url_for`. This method is preferred over hard-coding URLs as it handles changes, escaping, and application root paths automatically, ensuring robust URL generation. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_8 LANGUAGE: python CODE: ``` from flask import url_for @app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user/<username>') def profile(username): return f'{username}\'s profile' with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) ``` LANGUAGE: text CODE: ``` / /login /login?next=/ /user/John%20Doe ``` ---------------------------------------- TITLE: Install Waitress for Flask Application DESCRIPTION: This snippet demonstrates the steps to set up a Python virtual environment, install your Flask application, and then install the Waitress WSGI server using pip, preparing your project for deployment. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/waitress.rst#_snippet_0 LANGUAGE: text CODE: ``` $ cd hello-app $ python -m venv .venv $ . .venv/bin/activate $ pip install . # install your application $ pip install waitress ``` ---------------------------------------- TITLE: Run Gunicorn with eventlet asynchronous worker DESCRIPTION: Shows how to start Gunicorn using the 'eventlet' worker type for asynchronous processing. This requires eventlet to be installed and your application code to utilize eventlet for any performance benefits. Ensure greenlet>=1.0 is installed. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_4 LANGUAGE: shell CODE: ``` $ gunicorn -k eventlet 'hello:create_app()' ``` ---------------------------------------- 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: Run Gunicorn with gevent asynchronous worker DESCRIPTION: Shows how to start Gunicorn using the 'gevent' worker type for asynchronous processing. This requires gevent to be installed and your application code to utilize gevent for any performance benefits. Ensure greenlet>=1.0 is installed. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_3 LANGUAGE: shell CODE: ``` $ gunicorn -k gevent 'hello:create_app()' ``` ---------------------------------------- TITLE: Create Flask Project Directory DESCRIPTION: This command creates the root directory for the Flask application, which will contain the application package and instance folder. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_0 LANGUAGE: none CODE: ``` $ mkdir flaskr ``` ---------------------------------------- TITLE: Logging Messages in Flask Applications DESCRIPTION: Flask provides a preconfigured logger accessible via `app.logger` for recording various levels of messages. This allows developers to log debugging information, warnings, and errors within their application. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_31 LANGUAGE: python CODE: ``` app.logger.debug('A value for debugging') app.logger.warning('A warning occurred (%d apples)', 42) app.logger.error('An error occurred') ``` ---------------------------------------- TITLE: Setup Celery Worker for Flask Background Tasks DESCRIPTION: This command sequence sets up a Python virtual environment, installs project dependencies, and starts the Celery worker process. The Celery worker is essential for processing background tasks submitted by the Flask application. SOURCE: https://github.com/pallets/flask/blob/main/examples/celery/README.md#_snippet_0 LANGUAGE: shell CODE: ``` $ python3 -m venv .venv $ . ./.venv/bin/activate $ pip install -r requirements.txt && pip install -e . $ celery -A make_celery worker --loglevel INFO ``` ---------------------------------------- TITLE: Using test_request_context for Unit Testing DESCRIPTION: Demonstrates how to use the `test_request_context` context manager to bind a test request to the current context, enabling unit testing of code that depends on the global `request` object. This allows for assertions on request attributes like path and method. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_15 LANGUAGE: python CODE: ``` from flask import request with app.test_request_context('/hello', method='POST'): # now you can do something with the request until the # end of the with block, such as basic assertions: assert request.path == '/hello' assert request.method == 'POST' ``` ---------------------------------------- TITLE: Running the Flask Development Server DESCRIPTION: This shell command shows how to run the simple Flask application created in the previous snippet using the 'flask run' command. It starts the development server, typically on http://127.0.0.1:5000. SOURCE: https://github.com/pallets/flask/blob/main/README.md#_snippet_1 LANGUAGE: shell CODE: ``` $ flask run * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` ---------------------------------------- TITLE: Flask Application Configuration API Reference DESCRIPTION: Detailed API documentation for key components and methods used in configuring a Flask application, including the Flask class constructor, configuration methods, and routing decorators. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_2 LANGUAGE: APIDOC CODE: ``` Flask Class Constructor: Flask(__name__, instance_relative_config=True) __name__: The name of the current Python module, used by Flask to locate paths. instance_relative_config: bool - If True, configuration files are relative to the instance folder, which is outside the package and holds local data (e.g., secrets, database). Config Object Methods and Attributes: app.config.from_mapping(mapping: dict) Purpose: Sets default configuration values for the application. Parameters: mapping: A dictionary of configuration key-value pairs. Attributes: SECRET_KEY: Used by Flask and extensions for data safety. Default 'dev' for development; should be overridden in production. DATABASE: Path where the SQLite database file will be saved, typically under app.instance_path. app.config.from_pyfile(filename: str, silent: bool = False) Purpose: Overrides default configuration with values from a Python file in the instance folder. Parameters: filename: The name of the Python file (e.g., 'config.py'). silent: bool - If True, errors are ignored if the file doesn't exist. Flask Instance Attributes: app.instance_path: The path Flask has chosen for the instance folder. This folder is not created automatically and must be ensured to exist (e.g., using os.makedirs). Routing Decorators: @app.route(rule: str, **options) Purpose: Creates a connection between a URL rule and a function that returns a response. Parameters: rule: The URL rule string (e.g., '/hello'). Usage: Applied as a decorator to a Python function, making that function handle requests to the specified URL. ``` ---------------------------------------- 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: Modifying Flask Response Object with make_response DESCRIPTION: Shows how to use `make_response` to explicitly create a response object from a view's return value, allowing modification of headers or other properties before returning it. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_27 LANGUAGE: python CODE: ``` from flask import make_response @app.errorhandler(404) def not_found(error): resp = make_response(render_template('error.html'), 404) resp.headers['X-Something'] = 'A value' return resp ``` ---------------------------------------- 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: Installing and Running a Custom Script DESCRIPTION: These shell commands show how to install a project with a custom script entry point in editable mode and then execute the custom script (`wiki`) directly. SOURCE: https://github.com/pallets/flask/blob/main/docs/cli.rst#_snippet_32 LANGUAGE: text CODE: ``` $ pip install -e . $ wiki run ``` ---------------------------------------- TITLE: Flask Cookies: Storing on Response DESCRIPTION: Demonstrates how to set a cookie on the client's browser by using `make_response` and `resp.set_cookie()`. Cookies are set on the response object before it's returned. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_23 LANGUAGE: python CODE: ``` from flask import make_response @app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp ``` ---------------------------------------- TITLE: Send GET Request and Assert Response with Flask Test Client DESCRIPTION: This Python example illustrates how to use Flask's test client to simulate a GET request to a specified route (`/posts`). It then asserts that a particular byte string (`<h2>Hello, World!</h2>`) is present within the response data, verifying the expected output from the application's view. SOURCE: https://github.com/pallets/flask/blob/main/docs/testing.rst#_snippet_2 LANGUAGE: python CODE: ``` def test_request_example(client): response = client.get("/posts") assert b"<h2>Hello, World!</h2>" in response.data ``` ---------------------------------------- TITLE: Adding WSGI Middleware to Flask App (Python) DESCRIPTION: Shows how to wrap the `app.wsgi_app` attribute with WSGI middleware, using `werkzeug.middleware.proxy_fix.ProxyFix` as an example. This method allows middleware integration while keeping the original `app` object accessible for configuration. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_33 LANGUAGE: python CODE: ``` from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) ``` ---------------------------------------- TITLE: Installing gevent for Flask application DESCRIPTION: Instructions to set up a Python virtual environment and install gevent, ensuring compatibility with `greenlet>=1.0` and `PyPy>=7.3.7` for proper context local functionality like `request`. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gevent.rst#_snippet_0 LANGUAGE: text CODE: ``` $ cd hello-app $ python -m venv .venv $ . .venv/bin/activate $ pip install . $ pip install gevent ``` ---------------------------------------- TITLE: Flask Error Handler with Tuple Return DESCRIPTION: Demonstrates how to define a custom error handler in Flask that returns a tuple containing the response and status code, overriding the default status. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_26 LANGUAGE: python CODE: ``` from flask import render_template @app.errorhandler(404) def not_found(error): return render_template('error.html'), 404 ``` ---------------------------------------- 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: Install Flask application wheel on production server DESCRIPTION: Demonstrates how to install the previously built Flask application wheel file (.whl) on a target machine using pip. This command installs the application along with its declared dependencies. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_2 LANGUAGE: shell CODE: ``` $ pip install flaskr-1.0.0-py3-none-any.whl ``` ---------------------------------------- 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: Clone and Checkout Flask Repository DESCRIPTION: Instructions to clone the Flask repository, navigate to the `flask` directory, and checkout a specific tagged version of the code for the Flaskr example, ensuring compatibility with documentation. SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_0 LANGUAGE: bash CODE: ``` $ git clone https://github.com/pallets/flask $ cd flask $ git tag # shows the tagged versions $ git checkout latest-tag-found-above $ cd examples/tutorial ``` ---------------------------------------- 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: 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: Accessing URL Parameters with request.args DESCRIPTION: Demonstrates how to retrieve parameters submitted in the URL query string (e.g., `?key=value`) using the `request.args` attribute. It recommends using the `.get()` method to safely access parameters and provide a default value, preventing `KeyError`. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_19 LANGUAGE: python CODE: ``` searchword = request.args.get('key', '') ``` ---------------------------------------- TITLE: Generate URLs for Static Files in Flask DESCRIPTION: Illustrates the use of Flask's `url_for` function with the special `'static'` endpoint to generate URLs for static assets. This function automatically constructs the correct path to files located within the application's `static/` directory, such as `style.css`. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_11 LANGUAGE: python CODE: ``` url_for('static', filename='style.css') ``` ---------------------------------------- TITLE: Start Flask Development Server DESCRIPTION: Demonstrates how to start the Flask development server using the `flask run` command. This command replaces the `Flask.run` method for most cases. It's important to note that this server is for development only and not suitable for production. SOURCE: https://github.com/pallets/flask/blob/main/docs/cli.rst#_snippet_1 LANGUAGE: console CODE: ``` $ flask --app hello run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` ---------------------------------------- TITLE: Define Flask Routes with Dynamic Variable Rules DESCRIPTION: Illustrates how to create dynamic URL segments in Flask routes using `<variable_name>` and type converters like `<int:post_id>` or `<path:subpath>`. The corresponding function receives these segments as keyword arguments, allowing for flexible URL patterns. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_6 LANGUAGE: python CODE: ``` from markupsafe import escape @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return f'User {escape(username)}' @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return f'Post {post_id}' @app.route('/path/<path:subpath>') def show_subpath(subpath): # show the subpath after /path/ return f'Subpath {escape(subpath)}' ``` ---------------------------------------- TITLE: Example Pytest Test Session Output DESCRIPTION: This snippet shows a typical output from running `pytest`, detailing the test session start, platform information, collected items, progress for each test file, and a final summary of passed tests and execution time. It illustrates the console feedback during test execution. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/tests.rst#_snippet_23 LANGUAGE: none CODE: ``` ========================= test session starts ========================== platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0 rootdir: /home/user/Projects/flask-tutorial collected 23 items tests/test_auth.py ........ [ 34%] tests/test_blog.py ............ [ 86%] tests/test_db.py .. [ 95%] tests/test_factory.py .. [100%] ====================== 24 passed in 0.64 seconds ======================= ``` ---------------------------------------- TITLE: Start Flask Application with Debug Mode DESCRIPTION: This command initiates the Flask development server for the 'flaskr' application, activating debug mode. Debug mode is crucial for development as it provides an interactive debugger on errors and automatically reloads the server upon code modifications, streamlining the development workflow. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_3 LANGUAGE: text CODE: ``` $ flask --app flaskr run --debug ``` ---------------------------------------- TITLE: Initialize and configure a Flask extension in Python DESCRIPTION: This example demonstrates the general pattern for using a Flask extension. It shows how to import the extension, create an instance, configure application-specific settings via `app.config`, and then initialize the extension with the Flask application instance using the `init_app` method. SOURCE: https://github.com/pallets/flask/blob/main/docs/extensions.rst#_snippet_0 LANGUAGE: Python CODE: ``` from flask_foo import Foo foo = Foo() app = Flask(__name__) app.config.update( FOO_BAR='baz', FOO_SPAM='eggs', ) foo.init_app(app) ``` ---------------------------------------- TITLE: Installing eventlet for Flask applications DESCRIPTION: This snippet provides shell commands to set up a Python virtual environment, install your Flask application, and then install the `eventlet` library. It ensures the necessary dependencies are met for asynchronous serving. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/eventlet.rst#_snippet_0 LANGUAGE: text CODE: ``` $ cd hello-app $ python -m venv .venv $ . .venv/bin/activate $ pip install . # install your application $ pip install eventlet ``` ---------------------------------------- TITLE: Install Pytest for Flask Application Testing DESCRIPTION: This snippet demonstrates how to install the `pytest` framework, a prerequisite for setting up and running tests for Flask applications, using the pip package manager. SOURCE: https://github.com/pallets/flask/blob/main/docs/testing.rst#_snippet_0 LANGUAGE: text CODE: ``` $ pip install pytest ``` ---------------------------------------- TITLE: Running Waitress with Flask App Factory (Shell) DESCRIPTION: Command to start the Waitress server binding to localhost (127.0.0.1). It uses the '--call' option to specify an app factory function ('module:factory') that Waitress should call to get the application instance. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/waitress.rst#_snippet_2 LANGUAGE: text CODE: ``` # equivalent to 'from hello import create_app; create_app()' $ waitress-serve --host 127.0.0.1 --call hello:create_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: Implement RESTful API with Flask MethodView DESCRIPTION: Provides a comprehensive example of building a RESTful API using Flask's `MethodView`. It defines `ItemAPI` for single resource operations (GET, PATCH, DELETE) and `GroupAPI` for collection operations (GET, POST), demonstrating how to dispatch requests to class methods based on HTTP verbs. SOURCE: https://github.com/pallets/flask/blob/main/docs/views.rst#_snippet_12 LANGUAGE: python CODE: ``` from flask.views import MethodView class ItemAPI(MethodView): init_every_request = False def __init__(self, model): self.model = model self.validator = generate_validator(model) def _get_item(self, id): return self.model.query.get_or_404(id) def get(self, id): item = self._get_item(id) return jsonify(item.to_json()) def patch(self, id): item = self._get_item(id) errors = self.validator.validate(item, request.json) if errors: return jsonify(errors), 400 item.update_from_json(request.json) db.session.commit() return jsonify(item.to_json()) def delete(self, id): item = self._get_item(id) db.session.delete(item) db.session.commit() return "", 204 class GroupAPI(MethodView): init_every_request = False def __init__(self, model): self.model = model self.validator = generate_validator(model, create=True) def get(self): items = self.model.query.all() return jsonify([item.to_json() for item in items]) def post(self): errors = self.validator.validate(request.json) if errors: return jsonify(errors), 400 db.session.add(self.model.from_json(request.json)) db.session.commit() return jsonify(item.to_json()) def register_api(app, model, name): item = ItemAPI.as_view(f"{name}-item", model) group = GroupAPI.as_view(f"{name}-group", model) app.add_url_rule(f"/{name}/<int:id>", view_func=item) app.add_url_rule(f"/{name}/", view_func=group) register_api(app, User, "users") register_api(app, Story, "stories") ``` ---------------------------------------- TITLE: Integrating Models and Views in Flask Extensions (Python) DESCRIPTION: This example illustrates a pattern for a Flask extension that needs to define views interacting with models provided by another extension (like Flask-SQLAlchemy). It shows how the model can be defined during the extension's initialization (`__init__`) and then passed to the view factory (`as_view`) when setting up the application. SOURCE: https://github.com/pallets/flask/blob/main/docs/extensiondev.rst#_snippet_3 LANGUAGE: python CODE: ``` class PostAPI(MethodView): def __init__(self, model): self.model = model def get(self, id): post = self.model.query.get(id) return jsonify(post.to_json()) class BlogExtension: def __init__(self, db): class Post(db.Model): id = db.Column(primary_key=True) title = db.Column(db.String, nullable=False) self.post_model = Post def init_app(self, app): api_view = PostAPI.as_view(model=self.post_model) db = SQLAlchemy() blog = BlogExtension(db) db.init_app(app) blog.init_app(app) ``` ---------------------------------------- TITLE: Run Flask Application with Waitress WSGI Server DESCRIPTION: These commands illustrate how to launch a Flask application using `waitress-serve`. The first example shows serving a direct application object, while the second demonstrates using an app factory pattern with the `--call` option. Both examples bind the server to the local loopback address `127.0.0.1`. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/waitress.rst#_snippet_1 LANGUAGE: text CODE: ``` # equivalent to 'from hello import app' $ waitress-serve --host 127.0.0.1 hello:app # equivalent to 'from hello import create_app; create_app()' $ waitress-serve --host 127.0.0.1 --call hello:create_app Serving on http://127.0.0.1:8080 ``` ---------------------------------------- TITLE: Create Flask Project Directory DESCRIPTION: This snippet shows the basic shell commands to create a new project directory named `flask-tutorial` and navigate into it. This is the initial step for setting up a new Flask application. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/layout.rst#_snippet_0 LANGUAGE: none CODE: ``` $ mkdir flask-tutorial $ cd flask-tutorial ``` ---------------------------------------- TITLE: Install Waitress WSGI server for Flask DESCRIPTION: Instructions to install Waitress, a production-ready WSGI server, into the virtual environment using pip. Waitress is recommended for serving Flask applications in production instead of the built-in development server. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_6 LANGUAGE: shell CODE: ``` $ pip install waitress ``` ---------------------------------------- TITLE: Example Flask Python Config File Content DESCRIPTION: Provides an example of the content for a Python configuration file that can be loaded by Flask's config object using `from_object` or `from_envvar`. Only uppercase variables are loaded. SOURCE: https://github.com/pallets/flask/blob/main/docs/config.rst#_snippet_10 LANGUAGE: Python CODE: ``` # Example configuration SECRET_KEY = '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf' ``` ---------------------------------------- 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: 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: Install Python build tool DESCRIPTION: Installs the 'build' tool using pip, which is necessary for creating distribution wheel files for Python applications. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_0 LANGUAGE: shell CODE: ``` $ pip install build ``` ---------------------------------------- TITLE: Define Flask Application Factory (Python) DESCRIPTION: This Python function `create_app` serves as the application factory for a Flask application. It initializes the Flask instance, configures default settings, handles instance-relative configuration, ensures the instance folder exists, and sets up a basic '/hello' route. This pattern is recommended for robust application structures, especially for testing and deployment. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/factory.rst#_snippet_1 LANGUAGE: python CODE: ``` import os from flask import Flask def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # a simple page that says hello @app.route('/hello') def hello(): return 'Hello, World!' return app ``` ---------------------------------------- TITLE: Understand Flask Trailing Slash Redirection Behavior DESCRIPTION: Explains how Flask handles trailing slashes in URLs, demonstrating that a route ending with a slash (`/projects/`) will redirect if accessed without it, while a route without a trailing slash (`/about`) will result in a 404 if accessed with one. This helps maintain unique URLs for SEO. SOURCE: https://github.com/pallets/flask/blob/main/docs/quickstart.rst#_snippet_7 LANGUAGE: python CODE: ``` @app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page' ``` ---------------------------------------- TITLE: Install Flask-MongoEngine DESCRIPTION: This snippet provides the command to install the Flask-MongoEngine library, which is a required dependency for integrating MongoDB with Flask applications using MongoEngine. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/mongoengine.rst#_snippet_0 LANGUAGE: bash CODE: ``` pip install flask-mongoengine ``` ---------------------------------------- TITLE: Install mod_wsgi and application in a virtual environment DESCRIPTION: This snippet provides the shell commands to set up a Python virtual environment, install your Flask application, and then install the `mod_wsgi` package within that environment, preparing it for deployment. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.rst#_snippet_0 LANGUAGE: text CODE: ``` $ cd hello-app $ python -m venv .venv $ . .venv/bin/activate $ pip install . $ pip install mod_wsgi ``` ---------------------------------------- TITLE: Running Gunicorn with Eventlet Worker (Shell) DESCRIPTION: This command starts Gunicorn using the 'eventlet' worker class for asynchronous request handling. It loads the Flask application via the 'create_app' factory function. Requires the 'eventlet' library installed. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_5 LANGUAGE: text CODE: ``` $ gunicorn -k eventlet 'hello:create_app()' ``` ---------------------------------------- TITLE: Running Flask application with gevent WSGI server DESCRIPTION: Demonstrates how to create a `wsgi.py` script to initialize the gevent `WSGIServer` and serve a Flask application on a specified host and port. Includes the shell command to execute the script and start the server. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gevent.rst#_snippet_1 LANGUAGE: python CODE: ``` from gevent.pywsgi import WSGIServer from hello import create_app app = create_app() http_server = WSGIServer(("127.0.0.1", 8000), app) http_server.serve_forever() ``` LANGUAGE: text CODE: ``` $ python wsgi.py ``` ---------------------------------------- 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: Define SQLAlchemy User Model and Table DESCRIPTION: This example defines a SQLAlchemy ORM User class mapped to a 'users' table. It includes class properties for querying, an initializer, a representation method, and the table schema definition with columns and constraints, demonstrating a typical ORM setup. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/sqlalchemy.rst#_snippet_8 LANGUAGE: Python CODE: ``` from sqlalchemy import Table, Column, Integer, String from sqlalchemy.orm import mapper from yourapplication.database import metadata, db_session class User(object): query = db_session.query_property() def __init__(self, name=None, email=None): self.name = name self.email = email def __repr__(self): return f'<User {self.name!r}>' users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String(50), unique=True), Column('email', String(120), unique=True) ) mapper(User, users) ``` ---------------------------------------- TITLE: Install Flask - Shell DESCRIPTION: Command to install the Flask package using pip within the activated virtual environment. SOURCE: https://github.com/pallets/flask/blob/main/docs/installation.rst#_snippet_4 LANGUAGE: Shell CODE: ``` $ pip install Flask ``` ---------------------------------------- TITLE: Install Python Project in Editable Development Mode DESCRIPTION: This command uses `pip` to install the current project in 'editable' or 'development' mode. This allows local code changes to be reflected immediately without needing to re-install, unless project metadata like dependencies are altered. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/install.rst#_snippet_1 LANGUAGE: none CODE: ``` $ pip install -e . ``` ---------------------------------------- TITLE: Install Sentry SDK for Flask DESCRIPTION: Install the `sentry-sdk` client with its Flask-specific dependencies using pip to enable error reporting. SOURCE: https://github.com/pallets/flask/blob/main/docs/errorhandling.rst#_snippet_0 LANGUAGE: text CODE: ``` $ pip install sentry-sdk[flask] ``` ---------------------------------------- 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: Run Pytest with Coverage Report (Coverage Shell) DESCRIPTION: Runs the test suite with coverage measurement enabled, generates a summary report in the console, and creates a detailed HTML report. The HTML report can be viewed in a browser to see which lines of code were executed by the tests. SOURCE: https://github.com/pallets/flask/blob/main/examples/tutorial/README.rst#_snippet_8 LANGUAGE: Shell CODE: ``` $ coverage run -m pytest $ coverage report $ coverage html # open htmlcov/index.html in a browser ``` ---------------------------------------- TITLE: Install Celery using pip DESCRIPTION: Instructions to install the Celery library from PyPI using the pip package manager. SOURCE: https://github.com/pallets/flask/blob/main/docs/patterns/celery.rst#_snippet_0 LANGUAGE: text CODE: ``` $ pip install celery ``` ---------------------------------------- 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: Create Virtual Environment (Windows) - Shell DESCRIPTION: Commands to create a project directory and a virtual environment named .venv within it on Windows using the py -3 -m venv command. SOURCE: https://github.com/pallets/flask/blob/main/docs/installation.rst#_snippet_1 LANGUAGE: Shell CODE: ``` > mkdir myproject > cd myproject > py -3 -m venv .venv ``` ---------------------------------------- TITLE: Create and Run a Simple Flask Hello World Application DESCRIPTION: This snippet demonstrates how to create a basic 'Hello, World!' web application using Flask. It initializes a Flask app, defines a route for the root URL, and returns a simple string. The second part shows how to run the Flask development server from the command line, making the application accessible via a web browser. SOURCE: https://github.com/pallets/flask/blob/main/README.md#_snippet_0 LANGUAGE: python CODE: ``` # save this as app.py from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" ``` LANGUAGE: bash CODE: ``` $ flask run * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` ---------------------------------------- TITLE: Run Gunicorn with Flask application module or app factory DESCRIPTION: Demonstrates how to start Gunicorn, specifying the Flask application entry point. You can use either a module and app variable (e.g., 'hello:app') or an app factory function (e.g., 'hello:create_app()'). The '-w' option sets the number of worker processes, typically 'CPU * 2'. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/gunicorn.rst#_snippet_1 LANGUAGE: shell CODE: ``` # equivalent to 'from hello import app' $ gunicorn -w 4 'hello:app' ``` LANGUAGE: shell CODE: ``` # equivalent to 'from hello import create_app; create_app()' $ gunicorn -w 4 'hello:create_app()' ``` ---------------------------------------- TITLE: Run Flask with Waitress production server DESCRIPTION: Command to start the Flask application using the Waitress WSGI server. It specifies how to call the application factory ('create_app') to obtain the Flask application object, making it accessible via HTTP. SOURCE: https://github.com/pallets/flask/blob/main/docs/tutorial/deploy.rst#_snippet_7 LANGUAGE: shell CODE: ``` $ waitress-serve --call 'flaskr:create_app' ``` ---------------------------------------- TITLE: Start mod_wsgi-express server with processes DESCRIPTION: This command shows how to start the `mod_wsgi-express` server, specifying the `wsgi.py` script containing your Flask application and configuring the number of worker processes to run, which can be adjusted based on CPU cores. SOURCE: https://github.com/pallets/flask/blob/main/docs/deploying/mod_wsgi.rst#_snippet_2 LANGUAGE: text CODE: ``` $ mod_wsgi-express start-server wsgi.py --processes 4 ``` |