{"id":89308,"date":"2020-12-16T19:10:19","date_gmt":"2020-12-16T19:10:19","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=89308"},"modified":"2022-04-27T21:08:33","modified_gmt":"2022-04-27T21:08:33","slug":"developing-python-with-visual-studio","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/python\/developing-python-with-visual-studio\/","title":{"rendered":"Developing Python with Visual Studio"},"content":{"rendered":"<p>Python has become one of the most beloved programming languages of all time. It is flexible, easy to learn and code, open-source, and supported in all the major operating systems out there. For example, it offers a wide range of frameworks and libraries developed by the community to support and facilitate web applications. If you&#8217;re a .NET developer, chances are that you have played around with Python already, but, did you know that you can create Python projects in Visual Studio?<\/p>\n<p>This article explores this feature via the creation of a Python web project. It&#8217;s important to note, however, that except for the ability to mix code from .NET and Python through projects such as IronPython, this won&#8217;t be the main focus here. Perhaps it will be for a future article.<\/p>\n<h2>Setting up<\/h2>\n<p>First, you need to make sure the Python workload is already installed for your Visual Studio IDE. Make sure to <a href=\"https:\/\/visualstudio.microsoft.com\/downloads\/\">download<\/a> and run the installer for the VS Community Edition. Once you open the installer, select the proper Python workload, as shown in Figure 1.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"721\" height=\"441\" class=\"wp-image-89309\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-36.png\" \/><\/p>\n<p><strong>Figure 1. Installing the Python workload<\/strong><\/p>\n<p>Proceed with the installation. Then, move on to the project creation step.<\/p>\n<h3>Project setup<\/h3>\n<p>Open Visual Studio, then go to <em>Create a new project<\/em> and select <em>Python<\/em> on the <em>Languages<\/em> combo box. Select the <em>Python Application<\/em> template on the listed options, as shown in Figure 2.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"788\" class=\"wp-image-89310\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-37.png\" \/><\/p>\n<p><strong>Figure 2. Selecting the Python project template<\/strong><\/p>\n<p>Hit <em>Next<\/em>, select a location, name your solution, and, finally, click the <em>OK<\/em> button. Use Figure 3 as a reference.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"788\" class=\"wp-image-89311\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-38.png\" \/><\/p>\n<p><strong>Figure 3. Configuring the project<\/strong><\/p>\n<p>When the process finishes, you\u2019ll be able to see the newly created project along with its config files. It\u2019s important to state that the structure of Python applications is slightly different from the ones you\u2019re used to dealing with .NET. Take a look at Figure 4 below.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"436\" height=\"322\" class=\"wp-image-89312\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-39.png\" \/><\/p>\n<p><strong>Figure 4. Project structure<\/strong><\/p>\n<p>There are a few highlights to take note of:<\/p>\n<ul>\n<li>Even though it is a Python project, Visual Studio preserves the solution structure common to all of its projects. That\u2019s why you may see the VS solution at the top of the structure, as well as a <em>.sln<\/em> file if you navigate directly into your project folders.<\/li>\n<li>Every Python project is represented by a <em>.pyproj<\/em> file extension.<\/li>\n<li>Among the auto-generated project files, it comes together with a single <em>.py<\/em> file. That\u2019s your starting point to create some Python code.<\/li>\n<li>The <em>Python Environments<\/em> node brings the list of dependencies available to each of the Python interpreters installed. When you open each node, you may see the full list. Any new dependency you add to the project appears here.<\/li>\n<\/ul>\n<p>When you open the <em>PythonApplication1.py<\/em> file, you\u2019ll see that it\u2019s empty. Let\u2019s run the classic <em>Hello World<\/em> example in Python to test it out.<\/p>\n<p>Place the following code snippet within the Python file:<\/p>\n<pre class=\"lang:none theme:none\">print(\"Hello World!\")<\/pre>\n<p>To run it, do as you would with any ordinary .NET application. Just hit the <em>Start<\/em> button available at the top bar, as shown in Figure 5.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"716\" height=\"122\" class=\"wp-image-89313\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-40.png\" \/><\/p>\n<p><strong>Figure 5. Starting up the application<\/strong><\/p>\n<p>Note also that the Python version used to run the program is displayed within the following combo box. If you have other versions installed, you can pick the one you desire here.<\/p>\n<p>When the program finishes loading, you may see a screen like shown in Figure 6.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"674\" height=\"361\" class=\"wp-image-89314\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-41.png\" \/><\/p>\n<p><strong>Figure 6. Hello World example in action<\/strong><\/p>\n<p>You can also import the same built-in libraries you\u2019re used to doing when coding with Python elsewhere. Take the following example that calculates the power of two numbers:<\/p>\n<pre class=\"lang:none theme:none\">import sys\r\nfrom math import pow\r\nprint(\"2\u00b2 = \", pow(2, 2))<\/pre>\n<p>First, import the sys module. Then, import the pow function contained within the math module. Figure 7 shows the result of this program execution.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"591\" height=\"305\" class=\"wp-image-89315\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-42.png\" \/><\/p>\n<p><strong>Figure 7. Python execution result<\/strong><\/p>\n<p>Visual Studio also understands the primary functions that compose the language and allow for code completion, which is something essential when coding with an IDE. Figure 8 illustrates how the auto-completion feature happens along with Visual Studio.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"677\" height=\"358\" class=\"wp-image-89316\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-43.png\" \/><\/p>\n<p><strong>Figure 8. Code completion within Visual Studio for Python<\/strong><\/p>\n<h3>The Interactive REPL<\/h3>\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Read%E2%80%93eval%E2%80%93print_loop\">REPL<\/a> stands for <em>read\u2013eval\u2013print loop<\/em>, which is a simple and interactive shell program to provide developers with an environment that takes inputs, executes them, and returns the results. Most programming languages support this feature.<\/p>\n<p>As with many other languages that Visual Studio offers support, Python\u2019s not different when it comes to interactive REPL.<\/p>\n<p>To open it, go to the menu <em>View &gt; Other Windows &gt; Python Interactive Windows<\/em> (or press <em>Alt + I<\/em>) and now you have a direct window to test your Python code. Figure 9 demonstrates a quick example of use.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"776\" height=\"296\" class=\"wp-image-89317\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-44.png\" \/><\/p>\n<p><strong>Figure 9.<\/strong> Python Interactive REPL in Visual Studio.<\/p>\n<p>It also identifies multiline code statements, like when you\u2019re defining a Python function and performs automatic indentation, as you can see in Figure 10. This way, you can test more complex code structures without a physical Python file.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"731\" height=\"258\" class=\"wp-image-89318\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-45.png\" \/><\/p>\n<p><strong>Figure 10.<\/strong> Creating a custom function within REPL.<\/p>\n<h3>Importing third-party packages<\/h3>\n<p>You can also import 3rd-party packages directly within Visual Studio. For example, say you\u2019d like to incorporate a few more complex mathematical formulas to your application via the <a href=\"https:\/\/numpy.org\/\">NumPy<\/a> library, which is used for scientific computing with Python.<\/p>\n<p>To do this, right-click the <em>Python Environments<\/em> node within your <em>Solution Explorer<\/em> window, and select the option <em>View All Python Environments<\/em>. Then, with your current Python version selected, make sure that Packages (PyPI) is selected. Type the name of the package you desire in the available field, as shown in Figure 11. Click <em>Enter<\/em>.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"452\" height=\"577\" class=\"wp-image-89319\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-46.png\" \/><\/p>\n<p><strong>Figure 11.<\/strong> Installing the NumPy package.<\/p>\n<p>A green loading bar will appear while the package is installing. When it\u2019s finished, you can check on the results alongside the <em>Output<\/em> window. When the installation is complete, go back to your code file and place the contents shown in Listing 1 there.<\/p>\n<p><strong>Listing 1.<\/strong> Making use of NumPy package.<\/p>\n<pre class=\"lang:none theme:none\">import sys\r\nimport numpy as np\r\na = np.arange(20)\r\nprint(a)\r\na = a.reshape(4, 5)\r\nprint(a)<\/pre>\n<p>The arange function returns evenly spaced values within a given interval. Values are generated within the half-open interval [<em>start, stop<\/em>]. The <code>reshape<\/code> function, in turn, gives a new shape to the array without modifying its values. Figure 12 shows the output of this program execution.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"632\" height=\"323\" class=\"wp-image-89320\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-47.png\" \/><\/p>\n<p><strong>Figure 12.<\/strong> Running a simple NumPy example.<\/p>\n<p>This example demonstrates how powerful it is to deal with project dependencies within Visual Studio as it is with other IDEs.<\/p>\n<h2>Building a web application with Django<\/h2>\n<p>Now\u2019s time to move on to a more robust application. Until now, you\u2019ve explored how Python works in a Visual Studio Console application, the main features, shortcuts, dependency management, etc. It\u2019s time to build something that resembles something useful in daily life &#8212; a web application made with <a href=\"https:\/\/www.djangoproject.com\/\">Django<\/a>.<\/p>\n<p>Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. One of the favorite choices for Python developers in terms of web applications. You may have noticed in the step where you created the Python project template, Visual Studio prompts a bunch of options related to Python frameworks, such as Django and Flask-based projects.<\/p>\n<p>Now to get back to the initial steps and create another application by selecting the menu <em>New &gt; Project<\/em>. When the window opens, make sure to have <em>Python<\/em> as the default language selected.<\/p>\n<p>You\u2019ve got an option to create an empty web project for generic Python web projects. However, stick with Django since it saves a lot of time in terms of configurations. Figure 13 illustrates this step.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"788\" class=\"wp-image-89321\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-48.png\" \/><\/p>\n<p><strong>Figure 13. Creating a new Django Web Project<\/strong><\/p>\n<p>Click <em>Next<\/em> and, in the following screen, give the project and solution a name, select the project location, and hit the <em>Create<\/em> button. Once the project is created, make sure to take some time to analyze its initial structure (Figure 14).<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"467\" height=\"656\" class=\"wp-image-89322\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-49.png\" \/><\/p>\n<p><strong>Figure 14. Initial structure &#8211; Django web project<\/strong><\/p>\n<p>Projects in Django are composed of one or more inner Django applications, resembling a monolithic model. As you can see in the image above, each project is located right below the solution. You can have as many as you wish.<\/p>\n<h3>Setting Up a Virtual Env<\/h3>\n<p>Python works with <a href=\"https:\/\/docs.python.org\/3\/tutorial\/venv.html\">virtual environments<\/a> (venvs), which are self-contained directory trees with a Python installation for a specific version of the language. This structure helps to separate the global installed Python environment from the ones you\u2019re using alongside your projects. They work as virtual workspaces.<\/p>\n<p>To add a venv to your <em>Python Environments<\/em> node, right-click the <em>Python Environments<\/em> node and select the option <em>Add Environment&#8230; <\/em>The window shown in Figure 15 will pop with a bunch of information, such as the name you want for the new environment, the Python version to use (3.8), and the location of the config files.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"1280\" height=\"845\" class=\"wp-image-89323\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-50.png\" \/><\/p>\n<p><strong>Figure 15. Adding a new virtual environment to Visual Studio<\/strong><\/p>\n<p>You can leave all the configs as they are and click the <em>Create<\/em> button. Just make sure to leave the <em>Set as current environment<\/em> checkbox checked. At the end of the process, your node will change to the following:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"448\" height=\"156\" class=\"wp-image-89324\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-51.png\" \/><\/p>\n<p><strong>Figure 16.<\/strong> New Python environment set.<\/p>\n<p>Great! You\u2019re no longer using the default global environment. This way, all the Python packages and changes you perform will be restricted to this env, so your app becomes fully isolated and does not impact the others.<\/p>\n<h3>The Django Project<\/h3>\n<p>You can break down everything in the DjangoWebProject1 folder, the project structure, like this:<\/p>\n<ul>\n<li><em>__init__.py<\/em>: Python needs a way to differentiate ordinary folders from Python-folders. The way it does this is via this file. When Python finds this empty file in a directory, it immediately understands it\u2019s Python-based.<\/li>\n<li><em>wsgi.py<\/em>: It\u2019s used for <a href=\"https:\/\/en.wikipedia.org\/wiki\/Web_Server_Gateway_Interface\">WSGI<\/a> (web server gateway interface) purposes. This example won\u2019t use it.<\/li>\n<li><em>settings.py<\/em>: As the name suggests, this file takes care of all the settings for a Django project, such as authentication, session management, etc. You can find the full list of supported settings <a href=\"https:\/\/docs.djangoproject.com\/en\/3.1\/ref\/settings\/\">here<\/a>.<\/li>\n<li><em>urls.py<\/em>: Here\u2019s where you must map the routes for your Django endpoints, usually for your app\u2019s pages.<\/li>\n<li><em>manage.py<\/em>: It\u2019s a root configuration file that deals with settings such as env variables, general exception handling, etc.<\/li>\n<\/ul>\n<h3>The Django App<\/h3>\n<p>The Django application, which is located under the <em>app<\/em> folder, comes in a separate Python-based package because Django projects can have one or more Django apps. It will make use of the <em>urls.py<\/em> file you\u2019ve just seen to route from the outer scope to the inner app\u2019s scopes.<\/p>\n<p>Among its main auto-generated folders and files, you can find:<\/p>\n<ul>\n<li>a <em>\/migrations<\/em> folder that takes care of the database scripts to automatically handle migrations back and forth.<\/li>\n<li>a <em>\/templates<\/em> folder to deal with the Django templates. Django templates are pieces of HTML that can receive dynamic variables to turn static pages into dynamic. See that a bunch of ready-to-use templates already come with it.<\/li>\n<li>a <em>forms.py<\/em> file to help you on building web forms in Python and set up things like authentication and validation rules.<\/li>\n<li>a <em>models.py<\/em> file to hold the Django <a href=\"https:\/\/docs.djangoproject.com\/en\/3.1\/topics\/db\/models\/\">models<\/a>, which are encapsulations of data objects to hold your business model information.<\/li>\n<li>a <em>tests.py<\/em> file to deal with unit testing.<\/li>\n<li>and a <em>views.py<\/em> file to create and manage your web pages, handle the requests, call the services and databases, and return the responses. They work as controllers.<\/li>\n<\/ul>\n<h2>Running the Project<\/h2>\n<p>Now you\u2019re ready to run the project and see how it works in action. Just click the <em>Web Server (Google Chrome)<\/em> button available at the top of the IDE. This will open a Chrome window and display the page shown in Figure 17.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"960\" height=\"1138\" class=\"wp-image-89325\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-52.png\" \/><\/p>\n<p><strong>Figure 17. Generated Django application.<\/strong><\/p>\n<p>To try out a change, go to the <em>views.py<\/em> file and substitute the <em>home<\/em> function with the following:<\/p>\n<p><strong>Listing 2.<\/strong> Adding a random-generated number to the response.<\/p>\n<pre class=\"lang:none theme:none\">def home(request):\r\n    \"\"\"Renders the home page.\"\"\"\r\n    assert isinstance(request, HttpRequest)\r\n    return render(\r\n        request,\r\n        'app\/index.html',\r\n        {\r\n            'title':'SimpleTalk - Django with Visual Studio',\r\n            'randomNumber': randint(0, 100),\r\n            'year':datetime.now().year,\r\n        }\r\n    )<\/pre>\n<p>You\u2019re changing the title value and adding a randomly generated integer value to a variable called randomNumber. This value will go directly into your HTML page template, the <em>index.html<\/em>. Don\u2019t forget to import the randint function at the beginning of the file:<\/p>\n<pre class=\"lang:none theme:none\">from random import randint<\/pre>\n<p>Then, open the <em>index.html<\/em> template file and change the <em>jumbotron<\/em> div content for the following:<\/p>\n<pre class=\"lang:c# theme:vs2012\">&lt;div class=\"jumbotron\"&gt;\r\n    &lt;h1&gt;{{ title }}&lt;\/h1&gt;\r\n    &lt;p class=\"lead\"&gt;Random number of the day: {{ randomNumber }}&lt;\/p&gt;\r\n    &lt;p&gt;&lt;a href=\"https:\/\/www.djangoproject.com\/\" class=\"btn btn-primary btn-large\"&gt;Learn more &amp;raquo;&lt;\/a&gt;&lt;\/p&gt;\r\n&lt;\/div&gt;<\/pre>\n<p>See, easy\u2026 isn\u2019t it? Now, check out the result in Figure 18.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"893\" height=\"408\" class=\"wp-image-89326\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2020\/12\/word-image-53.png\" \/><\/p>\n<p><strong>Figure 18. Changing some values to the index template<\/strong><\/p>\n<h2>Conclusion<\/h2>\n<p>There\u2019s a whole lot more to see regarding Python development within Visual Studio. This was just a brief introduction to the main concepts and steps you\u2019d have to take to get things started.<\/p>\n<p>I can\u2019t stress enough the need of going through the <a href=\"https:\/\/docs.python.org\/\">Python<\/a> and <a href=\"https:\/\/docs.djangoproject.com\/en\/3.1\/\">Django<\/a> official documentation, to guide you every time you feel lost. Or even to start with the language + framework.<\/p>\n<p>What about you? How was your experience using Python along with Visual Studio? Leave your thoughts in the comments section and let\u2019s discuss it. Good studies!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python has become a popular language because of it\u2019s simplicity and vast library support. In this article, Julio Sampaio demonstrates how to get started creating Python apps in Visual Studio.&hellip;<\/p>\n","protected":false},"author":323407,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[146042],"tags":[5134],"coauthors":[93894],"class_list":["post-89308","post","type-post","status-publish","format-standard","hentry","category-python","tag-sql-prompt"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/89308","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/323407"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=89308"}],"version-history":[{"count":2,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/89308\/revisions"}],"predecessor-version":[{"id":89328,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/89308\/revisions\/89328"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=89308"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=89308"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=89308"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=89308"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}