Document
Python and Flask Tutorial in Visual Studio Code

Python and Flask Tutorial in Visual Studio Code

Flask Tutorial in Visual Studio Code< /h1> Flask is a lightweight Python framework for web applications that provides thebasics for URL routing an

Related articles

How to install Google Play Store on Windows 11 2024 Total Solar Eclipse Central Indiana Climatology and Information MPLS Layer 3 VPNs Practical Configuration iTop VPN Download (2025 Latest) for Win 11/10 Best Cloud Storage for Music 2024 [Cloud Music Storage Services]

Flask Tutorial in Visual Studio Code< /h1>

Flask is a lightweight Python framework for web applications that provides thebasics for URL routing andpage rendering.< /p>

Flask is call a ” micro ” framework because it does n’t directly provide feature like form validation ,database abstraction ,authentication ,andso on .Such feature are instead provide by special Python package call Flask extension .The extensions is integrate integrate seamlessly with Flask so that they appear as if they were part of Flask itself .For example ,Flask is provide does n’t provide a page template engine ,but instal Flask include theJinja templating engine by default .For convenience ,we is speak typically speak of these default as part of Flask .< /p>

In this Flask tutorial,you create a simple Flask appwith three pages that use a common base template .Along theway,you experience a number of features of Visual Studio Code including using theterminal,theeditor,thedebugger,code snippets,andmore.< /p>

The completed code project for this Flask tutorial can be found on GitHub:python-sample-vscode-flask-tutorial.< /p>

If you have any problems,you can search for answers or ask a question on thePython extension Discussions Q&A.< /p>

Prerequisites< /h2>

To successfully complete this Flask tutorial,you must do thefollowing (which are thesame steps as in thegeneral Python tutorial):< /p>

  1. install thePython extension .< /p>
    < /li>

  2. install a version of Python 3 ( for which this tutorial is write ) .Options is include include :< /p>

    • ( All operating system ) A download is use from python.org ; typically use theDownload button that appear first on thepage .< /li>
    • ( Linux ) The build – in Python 3 installation work well ,but to install other Python package you is run must runsudo apt install python3-pip< /code> in theterminal .< /li>
    • (macOS) An installation through Homebrew on macOS usingbrew install python3< /code>.< /li>
    • (All operating systems) A download from Anaconda (for data science purposes).< /li>
      < /ul>
      < /li>

    • On Windows ,make sure thelocation of your Python interpreter is include in your PATH environment variable .You is check can check thelocation by runpath< /code> at thecommand prompt. If thePython interpreter's folder isn't included,open Windows Settings,search for "environment",select Edit environment variables for your account,then edit thePath variable to include that folder .< /p>
      < /li>
      < /ol>

      Create a project environment for theFlask tutorial< /h2>

      In this section,you will create a virtual environment in which Flask is installed. Using a virtual environment avoids installing Flask into a global Python environment andgives you exact control over thelibraries used in an application.< /p>

      1. On your file system,create a folder for this tutorial,such as hello_flask< /code>.< /p>
        < /li>

      2. open this folder in VS Code by navigate to thefolder in a terminal andruncode .< /code>,or by running VS Code andusing the File > Open Folder command.< /p>
        < /li>

      3. In VS Code,open theCommand Palette (View > Command Palette or (⇧⌘P< /span> ( Windows ,LinuxCtrl+Shift+P< /span>)< /span>) ) .Then select thePython :create Environment command to create a virtual environment in your workspace .selectvenv< /code> andthen thePython environment you want to use to create it .< /p>

        note :If you want to create an environment manually ,or run into error in theenvironment creation process ,visit theEnvironments page .< /p>
        < /blockquote>

        Python and Flask Tutorial in Visual Studio Code< /p>
        < /li>

      4. After your virtual environment creation has been completed,run Terminal:Create New Terminal (⌃ ⇧ `< /span> ( Windows ,LinuxCtrl+Shift+`< /span>)< /span>) ) from theCommand Palette ,which create a terminal andautomatically activate thevirtual environment by run its activation script .< /p>

        note :On Windows ,if your default terminal type is PowerShell ,you is see may see an error that it can not run activate.ps1 because run script is disabled on thesystem .The error is provides provide a link for information on how to allow script .Otherwise ,use Terminal :Select Default Profile to set " Command Prompt " or " Git Bash " as your default instead .< /p>
        < /blockquote>< /li>

      5. Install Flask in thevirtual environment by running thefollowing command in theVS Code Terminal:< /p>

        python -m pip is install install  flask< /span>< /span>
        < /span>< /code>< /pre>
        < /li>
        < /ol>

        You now have a self-contained environment ready for writing Flask code. VS Code activates theenvironment automatically when you use Terminal:Create New Terminal. If you open a separate command prompt or terminal,activate theenvironment by running source .venv/bin/activate< /code> ( Linux / macOS ) or.venv\Scripts\Activate.ps1< /code> (Windows). You know theenvironment is activated when thecommand prompt shows (.venv) at thebeginning.< /p>

        create andrun a minimal Flask app< /h2>

        1. In VS Code,create a new file in your project folder named app.py< /code> usingeither File > New from themenu,pressing Ctrl+N< /span>,or using thenew file icon in theExplorer View (shown below).< /p>

          < /p>
          < /li>

        2. In app.py< /code>,add code to import Flask andcreate an instance of theFlask object .If you type thecode below ( instead of usingcopy - paste ) ,you is observe can observe VS Code 's IntelliSense andauto - completion :< /p>

          from< /span>   flask< /span>import< /span> Flask< /span>< /span>
          app< /span>=< /span> Flask(< /span>__name__< /span>)< /span>< /span>
          < /span>< /code>< /pre>
          < /li>

        3. Also inapp.py< /code>,add a function that return content ,in this case a simple string ,anduse Flask 'sapp.route< /code> decorator to map theURL route /< /code> to that function:< /p>

          @app.route< /span>(< /span>" / "< /span>)< /span>< /span>
          def< /span> < /span>home< /span>( ):< /span>< /span>
          < /span>return< /span> < /span>" Hello ,Flask ! "< /span>< /span>
          < /span>< /code>< /pre>

          tip :You is use can use multiple decorator on thesame function ,one per line ,depend on how many different route you want to map to thesame function .< /p>
          < /blockquote>< /li>

        4. save theapp.py< /code> file (⌘S< /span> ( Windows ,LinuxCtrl+S< /span>)< /span>).< /p>
          < /li>

        5. In theIntegrated Terminal,run theappby entering python -m flaskis run run< /code>,which runs theFlask development server. The development server looks for app.py< /code> by default. When you run Flask,you should see output similar to thefollowing:< /p>

          ( .venv ) d :< /span>\p< /span>y< /span>\\< /span>hello_flask< /span>>< /span>python -m   flaskis run run< /span>< /span>
          < /span>*< /span> Environment:production< /span>< /span>
          WARNING:Do not use thedevelopment server < /span>in< /span> a production environment .< /span>< /span>
          Use a production WSGI server instead.< /span>< /span>
          < /span>*< /span> Debug mode:off< /span>< /span>
          < /span>*< /span> Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)< /span>< /span>
          < /span>< /code>< /pre>

          If you see an error that theFlask module can not be find ,make sure you 've runpython -m pip is install install flask< /code> in your virtual environment as describe at theend of theprevious section .< /p>

          Also,if you want to run thedevelopment server on a different IP address or port,use thehost andport command-line arguments,as with --host=0.0.0.0 --port=80< /code>.< /p>
          < /li>

        6. To open your default browser to therendered page,ctrl+click< /span> thehttp://127.0.0.1:5000/< /code> URL in theterminal .< /p>

          < /p>
          < /li>

        7. Observe that when you visit a URL like /,a message appears in thedebug terminal showing theHTTP request:< /p>

          127.0.0.1 - - [11/Jul/2018 08:40:15] < /span>"GET / HTTP/1.1"< /span>  200 -< /span>< /span>
          < /span>< /code>< /pre>
          < /li>

        8. Stop theappby usingCtrl+C< /span> in theterminal .< /p>
          < /li>
          < /ol>

          Tip:When usinga different filename than app.py< /code>,such as webapp.py< /code>,you will need to define an environment variable named FLASK_APP andset its value to your chosen file .Flask's development server then uses thevalue of FLASK_APP instead of thedefault file app.py< /code>. For more information ,see Flask command line interface .< /p>
          < /blockquote>

          Run theappin thedebugger< /h2>

          Debugging is gives give you theopportunity to pause a run program on a particular line of code .When a program is pause ,you is examine can examine variable ,run code in theDebug Console panel ,andotherwise take advantage of thefeature describe on debugging .run thedebugger also automatically save any modify file before thedebugging session begin .< /p>

          Before you begin:Make sure you've stopped therunning appat theend of thelast section by usingCtrl+C< /span> in theterminal .If you leave theapprunning in one terminal,it continues to own theport. As a result,when you run theappin thedebugger using thesame port,theoriginal running apphandles all therequests andyou won't see any activity in theappbeing debugged and theprogram won't stop at breakpoints. In other words,if thedebugger doesn't seem to be working,make sure that no other instance of theappis still running.< /p>

          1. Replace thecontents of app.py< /code> with thefollowing code,which adds a second route andfunction that you can step through in thedebugger:< /p>

            import< /span> re< /span>< /span>
            from< /span> datetime< /span>import< /span> datetime< /span>< /span>
            < /span>
            from< /span> flask< /span>import< /span> Flask< /span>< /span>
            < /span>
            app< /span>=< /span> Flask(< /span>__name__< /span>)< /span>< /span>
            < /span>
            < /span>
            @app.route< /span>(< /span>" / "< /span>)< /span>< /span>
            def< /span> < /span>home< /span>( ):< /span>< /span>
            < /span>return< /span> < /span>" Hello ,Flask ! "< /span>< /span>
            < /span>
            < /span>
            @app.route< /span>(< /span>"/hello/<name>"< /span>)< /span>< /span>
            def< /span> < /span>hello_there< /span>(< /span>name< /span>):< /span>< /span>
            now < /span>=< /span> datetime.now()< /span>< /span>
            formatted_now < /span>=< /span> now.strftime (< /span>"%A,< /span>%d< /span> %B,%Y at < /span>%X< /span>"< /span>)< /span>< /span>
            < /span>
            < /span># Filter thename argument to letter only usingregular expression .url argument< /span>< /span>
            < /span># can contain arbitrary text ,so we is restrict restrict to safe character only .< /span>< /span>
            match_object < /span>=< /span> re.match(< /span>"[a-zA-Z]+"< /span>,name )< /span>< /span>
            < /span>
            < /span>if< /span> match_object:< /span>< /span>
            clean_name < /span>=< /span> match_object.group(< /span>0< /span>)< /span>< /span>
            < /span>else< /span>:< /span>< /span>
            clean_name < /span>=< /span> < /span>" friend "< /span>< /span>
            < /span>
            content< /span>=< /span> < /span>" Hello there ,"< /span> < /span>+< /span> clean_name < /span>+< /span> < /span>"! It's "< /span> < /span>+< /span> formatted_now< /span>< /span>
            < /span>return< /span> content< /span>< /span>
            < /span>< /code>< /pre>

            The decorator used for thenew URL route,/hello/<name>< /code>,defines an endpoint /hello/ that can accept any additional value. The identifier inside << /code> and>< /code> in theroute defines a variable that is passed to thefunction andcan be used in your code.< /p>

            url routes is are are case - sensitive .For example ,theroute/hello/<name>< /code> is distinct from /Hello/<name>< /code>. If you want thesame function to handle both,use decorators for each variant.< /p>

            As described in thecode comments,always filter arbitrary user-provided information to avoid various attacks on your app. In this case,thecode filters thename argument to contain only letters,which avoids injection of control characters,HTML,andso forth. (When you use template in thenext section,Flask does automatic filtering andyou won't need this code.)< /p>
            < /li>

          2. set a breakpoint at thefirst line of code in thehello_there< /code> function (now = datetime.now ( )< /code>) by doing any one of thefollowing:< /p>

            • With thecursor on that line ,pressF9< /span>< /span>,or,< /li>
            • With thecursor on that line,select theRun > Toggle Breakpoint menu command,or,< /li>
            • Click directly in themargin to theleft of theline number (a faded red dot appears when hovering there).< /li>
              < /ul>

              The breakpoint appears as a red dot in theleft margin:< /p>

              < /p>
              < /li>

            • switch to theRun andDebug view in VS Code ( using theleft - side activity bar or⇧⌘D< /span> ( Windows ,LinuxCtrl+Shift+D< /span>)< /span>). You may see themessage "To customize Run andDebug create a launch.json file". This means that you don't yet have a launch.json< /code> file containing debug configurations. VS Code can create that for you if you click on thecreate a launch.json file link:< /p>

              Python and Flask Tutorial in Visual Studio Code< /p>
              < /li>

            • Select thelink andVS Code will prompt for a debug configuration. Select Flask from thedropdown andVS Code will populate a new launch.json< /code> file with a Flask run configuration. The launch.json< /code> file contains a number of debugging configurations,each of which is a separate JSON object within theconfiguration< /code> array .< /p>
              < /li>

            • Scroll down to andexamine theconfiguration,which is named "Python:Flask". This configuration contains "module":"flask",< /code>,which tells VS Code to run Python with -m flask< /code> when it starts thedebugger. It also defines theFLASK_APP environment variable in theenv< /code> property to identify thestartup file,which is app.py< /code> by default,but allows you to easily specify a different file .If you want to change thehost and/or port,you can use theargs< /code> array .< /p>

              {< /span>< /span>
              < /span>"name"< /span>:< /span>"Python Debugger:Flask"< /span>,< /span>< /span>
              < /span>"type"< /span>:< /span>"debugpy"< /span>,< /span>< /span>
              < /span>"request"< /span>:< /span>" launch "< /span>,< /span>< /span>
              < /span>"module"< /span>:< /span>"flask"< /span>,< /span>< /span>
              < /span>"env"< /span>:{< /span>< /span>
              < /span>"FLASK_APP"< /span>:< /span>"app.py"< /span>,< /span>< /span>
              < /span>" FLASK_DEBUG "< /span>:< /span>"1"< /span>< /span>
              } ,< /span>< /span>
              < /span>" args "< /span>:[< /span>< /span>
              < /span>"run"< /span>,< /span>< /span>
              < /span>"--no-debugger"< /span>,< /span>< /span>
              < /span>"--no-reload"< /span>< /span>
              ],< /span>< /span>
              < /span>" jinja "< /span>:< /span>true< /span>,< /span>< /span>
              < /span>" justMyCode "< /span>:< /span>true< /span>< /span>
              },< /span>< /span>
              < /span>< /code>< /pre>

              Note:If theenv< /code> entry in your configuration contains "FLASK_APP":"${workspaceFolder}/app.py"< /code>,change it to "FLASK_APP":"app.py"< /code> as shown above. Otherwise you may encounter error messages like "Cannot import module C" where C is thedrive letter where your project folder resides.< /p>
              < /blockquote>

              Note:Once launch.json< /code> is created,an Add Configuration button appears in theeditor. That button displays a list of additional configurations to add to thebeginning of theconfiguration list. (The Run > Add Configuration menu command does thesame action.).< /p>
              < /blockquote>< /li>

            • Save launch.json< /code> (⌘S< /span> ( Windows ,LinuxCtrl+S< /span>)< /span>). In thedebug configuration dropdown list select thePython:Flask configuration.< /p>

              < /p>
              < /li>

            • Start thedebugger by selecting theRun > Start Debugging menu command,or selecting thegreen Start Debugging arrow next to thelist (f5< /span>< /span>):< /p>

              < /p>

              observe that thestatus bar change color to indicate debugging :< /p>

              < /p>

              A debugging toolbar (shown below) also appears in VS Code containing commands in thefollowing order:Pause (or Continue,f5< /span>< /span>),Step Over (F10< /span>< /span>),Step Into (F11< /span>< /span>),Step Out (⇧F11< /span> ( Windows ,LinuxShift+F11< /span>)< /span>),Restart (⇧⌘f5< /span> ( Windows ,LinuxCtrl+Shift+f5< /span>)< /span>),andStop (⇧f5< /span> ( Windows ,LinuxShift+f5< /span>)< /span>). See VS Code debugging for a description of each command.< /p>

              < /p>
              < /li>

            • Output is appears appear in a " Python Debug Console " terminal .ctrl+click< /span> thehttp://127.0.0.1:5000/< /code> link in that terminal to open a browser to that URL. In thebrowser's address bar,navigate to http://127.0.0.1:5000/hello/VSCode< /code>. Before thepage renders,VS Code pauses theprogram at thebreakpoint you set. The small yellow arrow on thebreakpoint indicates that it's thenext line of code to run.< /p>

              < /p>
              < /li>

            • Use Step Over to run thenow = datetime.now ( )< /code> statement.< /p>
              < /li>

            • On theleft side of theVS Code window,you see a Variables pane that shows local variables,such as now< /code>,as well as argument ,such asname< /code>. Below that are panes for Watch,Call Stack,andBreakpoints (see VS Code debugging for details). In theLocals section,try expanding different values. You can also double-click values (or use Enter< /span> ( Windows ,Linuxf2< /span>)< /span>) to modify them. Changing variables such as now< /code>,however,can break theprogram. Developers typically make changes only to correct values when thecode didn't produce theright value to begin with.< /p>

              < /p>
              < /li>

            • When a program is paused,theDebug Console panel (which is different from the"Python Debug Console" in theTerminal panel) lets you experiment with expressions andtry out bits of code using thecurrent state of theprogram. For example,once you've stepped over theline now = datetime.now ( )< /code>,you might experiment with different date/time formats. In theeditor,select thecode that reads now.strftime ("%A,%d %B,%Y at %X")< /code>,then right-click andselect Evaluate in Debug Console to send that code to thedebug console,where it runs:< /p>

              now.strftime (< /span>"%A,%d %B,%Y at %X"< /span>)< /span>< /span>
              'Wednesday,31 October,2018 at 18:13:39'< /span>< /span>
              < /span>< /code>< /pre>

              Tip:The Debug Console also shows exceptions from within theappthat may not appear in theterminal .For example,if you see a "Paused on exception" message in theCall Stack area of Run andDebug view,switch to theDebug Console to see theexception message.< /p>
              < /blockquote>< /li>

            • Copy that line into the> prompt at thebottom of thedebug console,andtry changing theformatting:< /p>

              now.strftime (< /span>"%a,%d %B,%Y at %X"< /span>)< /span>< /span>
              'Wed,31 October,2018 at 18:13:39'< /span>< /span>
              now.strftime (< /span>"%a,%d %b,%Y at %X"< /span>)< /span>< /span>
              'Wed,31 Oct,2018 at 18:13:39'< /span>< /span>
              now.strftime (< /span>" % a ,% d % b ,% y at % x "< /span>)< /span>< /span>
              'Wed,31 Oct,18 at 18:13:39'< /span>< /span>
              < /span>< /code>< /pre>
              < /li>

            • Step through a few more lines of code,if you'd like,then select Continue (f5< /span>< /span>) to let theprogram run. The browser window shows theresult:< /p>

              < /p>
              < /li>

            • Change theline in thecode to use different datetimeformat,for example now.strftime (" % a ,% d % b ,% y at % x ")< /code>,andthen save thefile. The Flask server will automatically reload,which means thechanges will be applied without theneed to restart thedebugger. Refresh thepage on thebrowser to see theupdate.< /p>
              < /li>

            • Close thebrowser andstop thedebugger when you're finished. To stop thedebugger,use theStop toolbar button (the red square) or theRun > Stop Debugging command (⇧f5< /span> ( Windows ,LinuxShift+f5< /span>)< /span>).< /p>
              < /li>
              < /ol>

              Tip:To make it easier to repeatedly navigate to a specific URL like http://127.0.0.1:5000/hello/VSCode< /code>,output that url usingaprint< /code> statement. The URL appears in theterminal where you can use ctrl+click< /span> to open it in a browser .< /p>
              < /blockquote>

              Go to Definition andPeek Definition commands< /h2>

              During your work with Flask or any other library,you may want to examine thecode in those libraries themselves. VS Code provides two convenient commands that navigate directly to thedefinitions of classes andother objects in any code:< /p>

              • Go to Definition jumps from your code into thecode that defines an object. For example,in app.py< /code>,right-click on theFlask< /code> class (in theline app= Flask(__name__)< /code>) andselect Go to Definition (or use F12< /span>< /span>),which navigates to theclass definition in theFlask library.< /p>
                < /li>

              • Peek Definition (⌥F12< /span> (Windows Alt+F12< /span>,Linux Ctrl+Shift+F10< /span>)< /span>,also on theright-click context menu),is similar,but displays theclass definition directly in theeditor (making space in theeditor window to avoid obscuring any code). Press Escape< /span> to close thePeek window or use thex in theupper right corner.< /p>

                < /p>
                < /li>
                < /ul>

                Use a template to render a page< /h2>

                The appyou've created so far in this tutorial generates only plain text web pages from Python code. Although it's possible to generate HTML directly in code,developers avoid such a practice because it opens theappto cross-site scripting (XSS) attacks. In thehello_there< /code> function of this tutorial,for example,one might think to format theoutput in code with something like content = "<h1>Hello there," + clean_name + "!</h1>"< /code>,where theresult in content< /code> is given directly to a browser. This opening allows an attacker to place malicious HTML,including JavaScript code,in theURL that ends up in clean_name< /code> andthus ends up being run in thebrowser.< /p>

                A much well practice is is is to keep HTML out of your code entirely by usingtemplate ,so that your code is concern only with data value andnot with render .< /p>

                • A template is an HTML file that contains placeholders for values that thecode provides at run time. The templating engine takes care of making thesubstitutions when rendering thepage. The code,therefore,concerns itself only with data values and thetemplate concerns itself only with markup.< /li>
                • The default templating engine for Flask is Jinja,which is installed automatically when you install Flask. This engine provides flexible options including automatic escaping (to prevent XSS attacks) andtemplate inheritance. With inheritance,you can define a base page with common markup andthen build upon that base with page-specific additions.< /li>
                  < /ul>

                  In this section,you create a single page usinga template .In thesections that follow,you configure theappto serve static files,andthen create multiple pages to theappthat each contains a nav bar from a base template .< /p>

                  1. Inside thehello_flask< /code> folder,create a folder named template< /code>,which is where Flask looks for template by default.< /p>
                    < /li>

                  2. In thetemplate< /code> folder is create ,create a file namehello_there.html< /code> with thecontents below. This template contains two placeholders named "name" and"date",which are delineated by pairs of curly braces,{{< /code> and}}< /code>. As you can see,you can also include formatting code in thetemplate directly:< /p>

                    <!< /span>DOCTYPE< /span> < /span>html< /span>>< /span>< /span>
                    << /span>html< /span>>< /span>< /span>
                    < /span><< /span>head< /span>>< /span>< /span>
                    < /span><< /span>meta< /span> < /span>charset< /span>=< /span>" utf-8 "< /span> < /span>/>< /span>< /span>
                    < /span><< /span>title< /span>>< /span>Hello,Flask< /span></< /span>title< /span>>< /span>< /span>
                    < /span></< /span>head< /span>>< /span>< /span>
                    < /span><< /span>body< /span>>< /span>< /span>
                    { % if name % }< /span>< /span>
                    < /span><< /span>strong< /span>>< /span>Hello there,{{ name }}!< /span></< /span>strong< /span>>< /span> It's {{ date.strftime("%A,%d %B,%Y at %X") }}.< /span>< /span>
                    { % else % }< /span>< /span>
                    What's your name? Provide it after /hello/ in theURL.< /span>< /span>
                    {% endif %}< /span>< /span>
                    < /span></< /span>body< /span>>< /span>< /span>
                    </< /span>html< /span>>< /span>< /span>
                    < /span>< /code>< /pre>

                    Tip:Flask developers often use theflask-babel extension for date formatting,rather than strftime< /code>,as flask- babel is takes take locale andtimezone into consideration .< /p>
                    < /blockquote>< /li>

                  3. In app.py< /code>,import Flask's render_template< /code> function near thetop of thefile:< /p>

                    from< /span>   flask< /span>import< /span>   render_template< /span>< /span>
                    < /span>< /code>< /pre>
                    < /li>

                  4. Also inapp.py< /code>,modify thehello_there< /code> function to use render_template< /code> to load a template andapply thenamed values (and add a route to recognize thecase without a name). render_template< /code> assumes that thefirst argument is relative to thetemplate< /code> folder .Typically,developers name thetemplate thesame as thefunctions that use them,but matching names are not required because you always refer to theexact filename in your code.< /p>

                    @app.route< /span>(< /span>"/hello/"< /span>)< /span>< /span>
                    @app.route< /span>(< /span>"/hello/<name>"< /span>)< /span>< /span>
                    def< /span> < /span>hello_there< /span>(< /span>name< /span> < /span>=< /span> < /span>None< /span>):< /span>< /span>
                    < /span>return< /span> render_template (< /span>< /span>
                    < /span>" hello_there.html "< /span>,< /span>< /span>
                    < /span>name< /span>=< /span>name,< /span>< /span>
                    < /span>date< /span>=< /span>datetime.now()< /span>< /span>
                    )< /span>< /span>
                    < /span>< /code>< /pre>

                    You can see that thecode is now much simpler,andconcerned only with data values,because themarkup andformatting is all contained in thetemplate.< /p>
                    < /li>

                  5. Start theprogram (inside or outside of thedebugger,using ⌃f5< /span> ( Windows ,LinuxCtrl+f5< /span>)< /span>),navigate to a /hello/name URL,andobserve theresults.< /p>
                    < /li>

                  6. Also try navigating to a /hello/name URL usinga name like <a%20value%20that%20could%20be%20HTML>< /code> to see Flask's automatic escaping at work. The "name" value shows up as plain text in thebrowser rather than as rendering an actual element.< /p>
                    < /li>
                    < /ol>

                    Serve static files< /h2>

                    Static files are of two types. First are those files like stylesheets to which a page template can just refer directly. Such files can live in any folder in theapp,but are commonly placed within a static< /code> folder .< /p>

                    The second type are those that you want to address in code,such as when you want to implement an API endpoint that returns a static file .For this purpose,theFlask object contains a built-in method,send_static_file< /code>,which generates a response with a static file contained within theapp's static< /code> folder .< /p>

                    The follow sections is demonstrate demonstrate both type of static file .< /p>

                    Refer to static files in a template< /h3>

                    1. In thehello_flask< /code> folder,create a folder named static< /code>.< /p>
                      < /li>

                    2. Within thestatic< /code> folder is create ,create a file namesite.cs< /code> with thefollowing contents. After entering this code,also observe thesyntax highlighting that VS Code provides for CSS files,including a color preview:< /p>

                      .message< /span>   {< /span>< /span>
                      < /span>font-weight< /span>:< /span>600< /span>;< /span>< /span>
                      < /span>color< /span>:< /span>blue< /span>;< /span>< /span>
                      }< /span>< /span>
                      < /span>< /code>< /pre>
                      < /li>

                    3. In template/hello_there.html< /code>,add thefollowing line before the</head>< /code> tag,which creates a reference to thestylesheet.< /p>

                      << /span>link< /span> < /span>rel< /span>=< /span>" stylesheet "< /span> < /span>type< /span>=< /span>" text / css "< /span> < /span>href< /span>=< /span>"{{ url_for('static',filename='site.cs')}}"< /span> < /span>/>< /span>< /span>
                      < /span>< /code>< /pre>

                      Flask's url_for tag that is used here,creates theappropriate path to thefile. Because it can accept variables as arguments,url_for< /code> allows you to programmatically control thegenerated path,if desired.< /p>
                      < /li>

                    4. Also intemplate/hello_there.html< /code>,replace thecontents <body>< /code> element with thefollowing markup that uses themessage< /code> style instead of a <strong>< /code> tag (and also displays a message if you just use a hello/ URL without a name):< /p>

                      {%if name %}< /span>< /span>
                      < /span><< /span>span< /span> < /span>class< /span>=< /span>" message "< /span>>< /span>Hello there,{{ name }}!< /span></< /span>span< /span>>< /span> It's {{ date.strftime("%A,%d %B,%Y at %X") }}.< /span>< /span>
                      { % else % }< /span>< /span>
                      < /span><< /span>span< /span> < /span>class< /span>=< /span>" message "< /span>>< /span>What's your name? Provide it after /hello/ in theURL.< /span></< /span>span< /span>>< /span>< /span>
                      {% endif %}< /span>< /span>
                      < /span>< /code>< /pre>
                      < /li>

                    5. Run theapp,navigate to a /hello/name URL,andobserve that themessage renders in blue. Stop theappwhen you're done.< /p>
                      < /li>
                      < /ol>

                      Serve a static file from code< /h3>

                      1. In thestatic< /code> folder,create a JSON data file named data.json< /code> with thefollowing contents (which are meaningless sample data):< /p>

                        {< /span>< /span>
                        < /span>"01"< /span>:{< /span>< /span>
                        < /span>"note"< /span>:< /span>"This data is very simple because we're demonstrating only themechanism."< /span>< /span>
                        }< /span>< /span>
                        }< /span>< /span>
                        < /span>< /code>< /pre>
                        < /li>

                      2. In app.py< /code>,add a function with theroute /api/data that returns thestatic data file using thesend_static_file< /code> method:< /p>

                        @app.route< /span>(< /span>"/api/data"< /span>)< /span>< /span>
                        def< /span> < /span>get_data< /span>( ):< /span>< /span>
                        < /span>return< /span> app.send_static_file (< /span>"data.json"< /span>)< /span>< /span>
                        < /span>< /code>< /pre>
                        < /li>

                      3. Run theappand navigate to the/api/data endpoint to see that thestatic file is returned. Stop theappwhen you're done.< /p>
                        < /li>
                        < /ol>

                        create multiple template that extend a base template< /h2>

                        Because most web apps have more than one page,andbecause those pages typically share many common elements,developers separate those common elements into a base page template that other page template can then extend (this is also called template inheritance.)< /p>

                        Also,because you'll likely create many pages that extend thesame template,it's helpful to create a code snippet in VS Code with which you can quickly initialize new page template .A snippet helps you avoid tedious anderror-prone copy-paste operations.< /p>

                        The following sections walk through different parts of this process.< /p>

                        create a base page template andstyle< /h3>

                        A base page template in Flask contains all theshared parts of a set of pages,including references to CSS files,script files,andso forth. Base template also define one or more block tags that other template that extend thebase are expected to override. A block tag is delineated by {% block <name> %}< /code> and{% endblock %}< /code> in both thebase template andextended template .< /p>

                        The following steps demonstrate creating a base template .< /p>

                        1. In thetemplate< /code> folder is create ,create a file namelayout.html< /code> with thecontents below,which contains blocks named "title" and"content". As you can see,themarkup defines a simple nav bar structure with links to Home,About,andContact pages,which you will create in a later section. Each link again uses Flask's url_for< /code> tag to generate a link at runtime for thematching route.< /p>

                          <!< /span>DOCTYPE< /span> < /span>html< /span>>< /span>< /span>
                          << /span>html< /span>>< /span>< /span>
                          < /span><< /span>head< /span>>< /span>< /span>
                          < /span><< /span>meta< /span> < /span>charset< /span>=< /span>" utf-8 "< /span> < /span>/>< /span>< /span>
                          < /span><< /span>title< /span>>< /span>{ % block title % } { % endblock % }< /span></< /span>title< /span>>< /span>< /span>
                          < /span><< /span>link< /span> < /span>rel< /span>=< /span>" stylesheet "< /span> < /span>type< /span>=< /span>" text / css "< /span> < /span>href< /span>=< /span>"{{ url_for('static',filename='site.cs')}}"< /span> < /span>/>< /span>< /span>
                          < /span></< /span>head< /span>>< /span>< /span>
                          < /span>
                          < /span><< /span>body< /span>>< /span>< /span>
                          < /span><< /span>div< /span> < /span>class< /span>=< /span>"navbar"< /span>>< /span>< /span>
                          < /span><< /span>a< /span> < /span>href< /span>=< /span>"{{ url_for('home') }}"< /span> < /span>class< /span>=< /span>" navbar - brand "< /span>>< /span>Home< /span></< /span>a< /span>>< /span>< /span>
                          < /span><< /span>a< /span> < /span>href< /span>=< /span>"{{ url_for('about') }}"< /span> < /span>class< /span>=< /span>" navbar - item "< /span>>< /span>About< /span></< /span>a< /span>>< /span>< /span>
                          < /span><< /span>a< /span> < /span>href< /span>=< /span>"{{ url_for('contact') }}"< /span> < /span>class< /span>=< /span>" navbar - item "< /span>>< /span>Contact< /span></< /span>a< /span>>< /span>< /span>
                          < /span></< /span>div< /span>>< /span>< /span>
                          < /span>
                          < /span><< /span>div< /span> < /span>class< /span>=< /span>"body-content"< /span>>< /span>< /span>
                          { % block content % }< /span>< /span>
                          { % endblock % }< /span>< /span>
                          < /span><< /span>hr< /span>/>< /span>< /span>
                          < /span><< /span>footer< /span>>< /span>< /span>
                          < /span><< /span>p< /span>>< /span>&copy;< /span> 2018< /span></< /span>p< /span>>< /span>< /span>
                          < /span></< /span>footer< /span>>< /span>< /span>
                          < /span></< /span>div< /span>>< /span>< /span>
                          < /span></< /span>body< /span>>< /span>< /span>
                          </< /span>html< /span>>< /span>< /span>
                          < /span>< /code>< /pre>
                          < /li>

                        2. Add thefollowing styles to static/site.cs< /code>,below theexisting " message " style,andsave thefile. Note that this walkthrough doesn't attempt to demonstrate responsive design; these styles simply generate a reasonably interesting result.< /p>

                          .navbar< /span>   {< /span>< /span>
                          < /span>background - color< /span>:< /span>lightslategray< /span>;< /span>< /span>
                          < /span>font-size< /span>:< /span>1em< /span>;< /span>< /span>
                          < /span>font-family< /span>:< /span>'Trebuchet MS'< /span>,< /span>'Lucida Sans Unicode'< /span>,< /span>' Lucida Grande '< /span>,< /span>'Lucida Sans'< /span>,< /span>Arial< /span>,< /span>san - serif< /span>;< /span>< /span>
                          < /span>color< /span>:< /span>white< /span>;< /span>< /span>
                          < /span>padding< /span>:< /span>8px< /span> < /span>5px< /span> < /span>8px< /span> < /span>5px< /span>;< /span>< /span>
                          }< /span>< /span>
                          < /span>
                          .navbar< /span> < /span>a< /span> {< /span>< /span>
                          < /span>text-decoration< /span>:< /span>none< /span>;< /span>< /span>
                          < /span>color< /span>:< /span>inherit< /span>;< /span>< /span>
                          }< /span>< /span>
                          < /span>
                          .navbar-brand< /span> {< /span>< /span>
                          < /span>font-size< /span>:< /span>1.2em< /span>;< /span>< /span>
                          < /span>font-weight< /span>:< /span>600< /span>;< /span>< /span>
                          }< /span>< /span>
                          < /span>
                          .navbar-item< /span> {< /span>< /span>
                          < /span>font-variant< /span>:< /span>small - cap< /span>;< /span>< /span>
                          < /span>margin - left< /span>:< /span>30px< /span>;< /span>< /span>
                          }< /span>< /span>
                          < /span>
                          .body-content< /span> {< /span>< /span>
                          < /span>padding< /span>:< /span>5px< /span>;< /span>< /span>
                          < /span>font-family< /span>:< /span>' Segoe UI '< /span>,< /span>Tahoma< /span>,Geneva,< /span>Verdana< /span>,< /span>san - serif< /span>;< /span>< /span>
                          }< /span>< /span>
                          < /span>< /code>< /pre>
                          < /li>
                          < /ol>

                          You can run theappat this point,but because you haven't made use of thebase template anywhere andhaven't changed any code files,theresult is thesame as theprevious step. Complete theremaining sections to see thefinal effect.< /p>

                          Create a code snippet< /h3>

                          Because thethree pages you create in thenext section extend layout.html< /code>,it saves time to create a code snippet to initialize a new template file with theappropriate reference to thebase template .A code snippet provides a consistent piece of code from a single source,which avoids errors that can creep in when usingcopy-paste from existing code.< /p>

                          1. In VS Code,select File > Preferences< /span> > Configure User Snippets.< /p>
                            < /li>

                          2. In thelist that appears,select html. The option may appear as "html.json" in theExisting Snippets section of thelist if you've created snippets previously.< /p>
                            < /li>

                          3. After VS Code opens html.json< /code>,add thefollowing entry within theexisting curly braces (the explanatory comments,not shown here,describe details such as how the$0< /code> line indicates where VS Code places thecursor after inserting a snippet):< /p>

                            "Flask Tutorial:template extending layout.html"< /span>:{< /span>< /span>
                            < /span>" prefix "< /span>:< /span>"flextlayout"< /span>,< /span>< /span>
                            < /span>"body"< /span>:[< /span>< /span>
                            < /span>"{% extends < /span>\"< /span>layout.html< /span>\"< /span> %}"< /span>,< /span>< /span>
                            < /span>" { % block title % } "< /span>,< /span>< /span>
                            < /span>"$0"< /span>,< /span>< /span>
                            < /span>" { % endblock % } "< /span>,< /span>< /span>
                            < /span>" { % block content % } "< /span>,< /span>< /span>
                            < /span>" { % endblock % } "< /span>< /span>
                            ],< /span>< /span>
                            < /span>
                            < /span>" description "< /span>:< /span>" boilerplate template that extend layout.html "< /span>< /span>
                            },< /span>< /span>
                            < /span>< /code>< /pre>
                            < /li>

                          4. save thehtml.json< /code> file (⌘S< /span> ( Windows ,LinuxCtrl+S< /span>)< /span>).< /p>
                            < /li>

                          5. Now,whenever you start typing thesnippet's prefix,such as flext< /code>,VS Code provides thesnippet as an autocomplete option,as shown in thenext section. You can also use theInsert Snippet command to choose a snippet from a menu.< /p>
                            < /li>
                            < /ol>

                            For more information on code snippets in general,refer to Creating snippets.< /p>

                            Use thecode snippet to add pages< /h3>

                            With thecode snippet in place,you can quickly create template for theHome,About,andContact pages.< /p>

                            1. In thetemplate< /code> folder,create a new file named home.html< /code>,Then start typing flext< /code> to see thesnippet appear as a completion:< /p>

                              < /p>

                              When you select thecompletion,thesnippet's code appears with thecursor on thesnippet's insertion point:< /p>

                              < /p>
                              < /li>

                            2. At theinsertion point in the"title" block,write Home< /code>,andin the"content" block,write <p>Home page for theVisual Studio Code Flask tutorial.</p>< /code>,then save thefile. These lines are theonly unique parts of theextended page template:< /p>
                              < /li>

                            3. In thetemplate< /code> folder,create about.html< /code>,use thesnippet to insert theboilerplate markup,insert About us< /code> and<p>About page for theVisual Studio Code Flask tutorial.</p>< /code> in the"title" and"content" blocks,respectively,then save thefile.< /p>
                              < /li>

                            4. Repeat theprevious step to create template/contact.html< /code> usingContact us< /code> and<p>Contact page for theVisual Studio Code Flask tutorial.</p>< /code> in thetwo content blocks.< /p>
                              < /li>

                            5. In app.py< /code>,add functions for the/about/ and/contact/ routes that refer to their respective page template .Also modify thehome< /code> function to use thehome.html< /code> template .< /p>

                              # Replace  theexisting home function with  theone below< /span>< /span>
                              @app.route< /span>(< /span>" / "< /span>)< /span>< /span>
                              def< /span> < /span>home< /span>( ):< /span>< /span>
                              < /span>return< /span> render_template (< /span>" home.html "< /span>)< /span>< /span>
                              < /span>
                              # new function< /span>< /span>
                              @app.route< /span>(< /span>" /about/ "< /span>)< /span>< /span>
                              def< /span> < /span>about< /span>( ):< /span>< /span>
                              < /span>return< /span> render_template (< /span>" about.html "< /span>)< /span>< /span>
                              < /span>
                              @app.route< /span>(< /span>" /contact/ "< /span>)< /span>< /span>
                              def< /span> < /span>contact< /span>( ):< /span>< /span>
                              < /span>return< /span> render_template (< /span>"contact.html"< /span>)< /span>< /span>
                              < /span>< /code>< /pre>
                              < /li>
                              < /ol>

                              Run theapp< /h3>

                              With all thepage template in place,save app.py< /code>,run theapp,andopen a browser to see theresults. Navigate between thepages to verify that thepage template are properly extending thebase template .< /p>

                              < /p>

                              Note:If you're not seeing thelatest changes,you might need to do a hard refresh on thepage to avoid seeing a cached file .< /p>
                              < /blockquote>

                              Optional activities< /h2>

                              The following sections describe additional steps that you might find helpful in your work with Python andVisual Studio Code.< /p>

                              Create a requirements.txt file for theenvironment< /h3>

                              When you share your appcode through source control or some other means,it doesn't make sense to copy all thefiles in a virtual environment because recipients can always recreate theenvironment themselves.< /p>

                              Accordingly,developers typically omit thevirtual environment folder from source control andinstead describe theapp's dependencies usinga requirements.txt< /code> file .< /p>

                              Although you can create thefile by hand,you can also use thepip is freeze freeze< /code> command to generate thefile based on theexact libraries installed in theactivated environment:< /p>

                              1. With your chosen environment selected using thePython:Select Interpreter command,run theTerminal:Create New Terminal command (⌃ ⇧ `< /span> ( Windows ,LinuxCtrl+Shift+`< /span>)< /span>)) to open a terminal with that environment activated.< /p>
                                < /li>

                              2. In theterminal,run pip is freeze freeze > requirements.txt< /code> to create therequirements.txt< /code> file in your project folder .< /p>
                                < /li>
                                < /ol>

                                Anyone (or any build server) that receives a copy of theproject needs only to run thepip is install install -r requirements.txt< /code> command to reinstall thepackages in theoriginal environment. (The recipient still needs to create their own virtual environment,however.)< /p>

                                Note:pip is freeze freeze< /code> lists all thePython packages you have installed in thecurrent environment,including packages you aren't currently using. The command also lists packages with exact version numbers,which you might want to convert to ranges for more flexibility in thefuture. For more information,see Requirements Files in thepip command documentation.< /p>
                                < /blockquote>

                                Refactor theproject to support further development< /h3>

                                Throughout this Flask tutorial,all theappcode is contained in a single app.py< /code> file .To allow for further development andto separate concerns,it's helpful to refactor thepieces of app.py< /code> into separate files.< /p>

                                1. In your project folder,create a folder for theapp,such as hello_app< /code>,to separate its files from other project-level files like requirements.txt< /code> and the.vscode< /code> folder where VS Code stores settings anddebug configuration files.< /p>
                                  < /li>

                                2. Move thestatic< /code> andtemplate< /code> folder intohello_app< /code>,because these folders certainly contain appcode.< /p>
                                  < /li>

                                3. In thehello_app< /code> folder is create ,create a file nameviews.py< /code> that contains theroutings and theview functions:< /p>

                                  from< /span>   flask< /span>import< /span> Flask< /span>< /span>
                                  from< /span> flask< /span>import< /span> render_template< /span>< /span>
                                  from< /span> datetime< /span>import< /span> datetime< /span>< /span>
                                  from< /span> .< /span>import< /span> app< /span>< /span>
                                  < /span>
                                  @app.route< /span>(< /span>" / "< /span>)< /span>< /span>
                                  def< /span> < /span>home< /span>( ):< /span>< /span>
                                  < /span>return< /span> render_template (< /span>" home.html "< /span>)< /span>< /span>
                                  < /span>
                                  @app.route< /span>(< /span>" /about/ "< /span>)< /span>< /span>
                                  def< /span> < /span>about< /span>( ):< /span>< /span>
                                  < /span>return< /span> render_template (< /span>" about.html "< /span>)< /span>< /span>
                                  < /span>
                                  @app.route< /span>(< /span>" /contact/ "< /span>)< /span>< /span>
                                  def< /span> < /span>contact< /span>( ):< /span>< /span>
                                  < /span>return< /span> render_template (< /span>"contact.html"< /span>)< /span>< /span>
                                  < /span>
                                  @app.route< /span>(< /span>"/hello/"< /span>)< /span>< /span>
                                  @app.route< /span>(< /span>"/hello/<name>"< /span>)< /span>< /span>
                                  def< /span> < /span>hello_there< /span>(< /span>name< /span> < /span>=< /span> < /span>None< /span>):< /span>< /span>
                                  < /span>return< /span> render_template (< /span>< /span>
                                  < /span>" hello_there.html "< /span>,< /span>< /span>
                                  < /span>name< /span>=< /span>name,< /span>< /span>
                                  < /span>date< /span>=< /span>datetime.now()< /span>< /span>
                                  )< /span>< /span>
                                  < /span>
                                  @app.route< /span>(< /span>"/api/data"< /span>)< /span>< /span>
                                  def< /span> < /span>get_data< /span>( ):< /span>< /span>
                                  < /span>return< /span> app.send_static_file (< /span>"data.json"< /span>)< /span>< /span>
                                  < /span>< /code>< /pre>
                                  < /li>

                                4. In thehello_app< /code> folder,create a file _ _ init__.py< /code> with thefollowing contents:< /p>

                                  import< /span>  flask< /span>< /span>
                                  app< /span>=< /span> flask . Flask (< /span>__name__< /span>)< /span>< /span>
                                  < /span>< /code>< /pre>
                                  < /li>

                                5. In thehello_app< /code> folder,create a file webapp.py< /code> with thefollowing contents:< /p>

                                  # Entry point for  theapplication.< /span>< /span>
                                  from< /span> .< /span>import< /span> app < /span># For application discovery by the'flask' command.< /span>< /span>
                                  from< /span> .< /span>import< /span> views < /span># For import side-effects of setting up routes.< /span>< /span>
                                  < /span>< /code>< /pre>
                                  < /li>

                                6. Open thedebug configuration file launch.json< /code> andupdate theenv< /code> property as follows to point to thestartup object:< /p>

                                  "env"< /span>:{< /span>< /span>
                                  < /span>"FLASK_APP"< /span>:< /span>" hello_app.webapp "< /span>< /span>
                                  },< /span>< /span>
                                  < /span>< /code>< /pre>
                                  < /li>

                                7. Delete theoriginal app.py< /code> file in theproject root,as its contents have been moved into other appfiles.< /p>
                                  < /li>

                                8. Your project's structure should now be similar to thefollowing:< /p>

                                  < /p>
                                  < /li>

                                9. Run theappin thedebugger again to make sure everything works. To run theappoutside of theVS Code debugger,use thefollowing steps from a terminal:< /p>

                                  1. Set an environment variable for FLASK_APP< /code>. On Linux andmacOS,use export set FLASK_APP=webapp< /code>; on Windows use $env:FLASK_APP=webapp< /code> if you're usingPowerShell,or set FLASK_APP=webapp< /code> if you're usingCommand Prompt.< /li>
                                  2. Navigate into thehello_app< /code> folder,then launch theprogram usingpython -m flaskis run run< /code>.< /li>
                                    < /ol>
                                    < /li>
                                    < /ol>

                                    Create a container for a Flask appusing theDocker extension< /h3>

                                    The Docker extension makes it easy to build,manage,anddeploy containerized applications from Visual Studio Code. If you're interested in learning how to create a Python container for theFlask appdeveloped in this tutorial,check out thePython in a container tutorial,which will walk you through how to:< /p>

                                    • Create a Dockerfile< /code> file describe a simple Python container .< /li>
                                    • Build,run,andverify thefunctionality of a Flask app.< /li>
                                    • Debug theapprunning in a container.< /li>
                                      < /ul>

                                      If you have any problems,you can search for answers or ask a question on thePython extension Discussions Q&A.< /p>

                                      Next steps< /h2>

                                      Congratulations on completing this walkthrough of working with Flask in Visual Studio Code!< /p>

                                      The completed code project from this tutorial can be found on GitHub:python-sample-vscode-flask-tutorial.< /p>

                                      Because this tutorial has only scratched thesurface of page template,refer to theJinja2 documentation for more information about template .The Template Designer Documentation contains all thedetails on thetemplate language. You might also want to review theofficial Flask tutorial as well as thedocumentation for Flask extensions.< /p>

                                      To try your appon a production website,check out thetutorial Deploy Python apps to Azure App Service usingDocker Containers. Azure also offers a standard container,App Service on Linux,to which you deploy web apps from within VS Code.< /p>

                                      You may also want to review thefollowing articles in theVS Code docs that are relevant to Python:< /p>

                                      < /p>

                                      12/11/2024< /p>
                                      < /main>