No results found
We couldn't find anything using that term, please try searching for something else.
Flask Tutorial in Visual Studio Code< /h1> Flask is a lightweight Python framework for web applications that provides thebasics for URL routing an
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>
To successfully complete this Flask tutorial,you must do thefollowing (which are thesame steps as in thegeneral Python tutorial):< /p>
install thePython extension .< /p>
< /li>
install a version of Python 3 ( for which this tutorial is write ) .Options is include include :< /p>
sudo apt install python3-pip< /code> in theterminal .< /li>
- (macOS) An installation through Homebrew on macOS using
brew 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>
-
On your file system,create a folder for this tutorial,such as hello_flask< /code>.< /p>
< /li>
-
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>
-
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>
< /p>
< /li>
-
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>
-
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>
-
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>
-
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>
-
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>
-
save theapp.py< /code> file (⌘S< /span> ( Windows ,LinuxCtrl+S< /span>)< /span>).< /p>
< /li>
-
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>
-
To open your default browser to therendered page,ctrl+click< /span> thehttp://127.0.0.1:5000/< /code> URL in theterminal .< /p>
< /p>
< /li>
-
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>
-
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>
-
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>
-
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>
< /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>