VSCode, Django, and Anaconda integrated development environment configuration [Windows]

  Prior has been carried out under Ubuntu Python and Django development, recently changed computers, to run under Virtual Box Ubuntu development machine always move over frequent crashes, simply to try to develop Windows environment moved to the main machine.

I have to say, giant hard home past few years in terms of diverse and package really is at the forefront of the world. In particular VSCode, two years ago it has become my main IDE under Linux. So Google directly to this cool article: Django Tutorial in Visual Studio Code, the following will combine Anaconda development environment, to translate this official guide.

 

0x1 - Installation Checklist

- Win10

- Anaconda3

- Vistual Studio Code(VSCode)

 Download separately and in accordance with good three or more artifacts, the election is the latest stable version.

 

0x2 - Anaconda manage and configure Python development environment

  • Open Anaconda Prompt Terminal command-line tool (not Anaconda Navigator), first to practice under conda, similar to the pip and virtualenv combination.

  • Create a virtual Python development environment with conda, pay attention to add python version after the name of the environment (here my_env).
conda create -n wechat_env python=3.7
  • Remove the environment

 conda remove -n wechat_env --all

  • View a list of virtual environments, virtual environments * represents the current working location:
(base) C:\Users\freman.zhang>conda env list
# conda environments:
#
base                  *  C:\Anaconda3
wechat_env C: \ Anaconda3 \ envs \ wechat_env
  •  Activation and switching environment:
(base) C:\Users\freman.zhang>conda activate wechat_env
(wechat_env) C:\Users\freman.zhang>conda env list
# conda environments:
#
base                     C:\Anaconda3
wechat_env            *  C:\Anaconda3\envs\wechat_env
(wechat_env) C:\Users\freman.zhang>conda deactivate
(base) C:\Users\freman.zhang>
  • To install Django development environment, if necessary, you can specify the version number.
conda install django
conda install django==2.2.5

 

 

Such conda will automatically download and install Python and Django to a specific development environment, no longer need to pre-install or separately in the OS.

c onda detailed management command to official documents detailed understanding.

 

0x3 - configuring the integrated development environment in the VSCode

 Senior Python framework Django is a safe, fast and scalable web development designed. Django provides a wealth of support for URL routing, page templates and data processing.

In the next tutorial, we'll create a simple three-page application, and will use a common base template. By VSCode in complete go over this development process, we will be able to better understand how to use VSCode command terminal, editor and debugger, etc. to carry out efficient and convenient Django application development.

The complete code for the entire sample project in Github:  Python-Django-the Sample-VSCode-the Tutorial .

1. Prepare conditions

- Install the python plug-in VScode

- download and install python, special attention needs to configure the PATH environment variable in Windows

Our installation kits and development environments have been completed by conda in front, it can very clearly reflect the convenience Anaconda in package management after contrast.

2. Integration of virtual development environment to VSCode

  • In VSCode press the key combination ctrl + shift + P, enter python, first select Python: Select Interpreter, this command will demonstrate a python interpreter list of all VSCode available.

 

  • We choose top with conda new development environment from this list - with ./env or .\env开头

 

 

  •  Press the key combination Ctrl + Shift + `to open a new terminal of the integrated command, the status bar at the point where VSCode, you can see to identify the current development environment

 

 

 0x4 - Create a Django project in VSCode

1. Press the key combination Ctrl + Shift + `to develop into the terminal, the relevant interpreter and virtual development environment will automatically be activated. Then execute the following command, if there is no error, open http://127.0.0.1:8000 browser, we will see the default Django welcome page.

django-admin startproject web_project C:\web_project
cd C:\web_project
python manage.py startapp hello
python manage.py runserver

 

 

 2. 接下来是Django应用的基础构建

  • hello/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, Django!")
  •  hello/urls.py
from django.urls import path
from hello import views

urlpatterns = [
    path("", views.home, name="home"),
]

 

  • web_project/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("", include("hello.urls")),
]

 

 

 

3. 保存所有文件,然后启动服务 python manage.py runserver,用浏览器访问应用网址 http://127.0.0.1:8000,将会看到如下:

 

 

 0x5 - VSCode中创建Django debugger launch profile开启自动调试

到这里你可能已经在想,是否有更好的方式来调试和运行应用服务,而非每次执行一次python manage.py runserver 呢?必须有的!

VSCode的debugger是支持Django的,我们通过自定义 launch profile就可以实现这一点。

1. 切换左边的活动栏到Debug, 在Debug视图的顶部,我们可以看到如下。No Configuratins表示Debugger还未配置任何运行设定(launch.json)。

 

 

 2. 点击齿轮创建并开启一个launch.json文件,这个文件里面已经包含了一些调试设定,每种都是以独立的JSON对象存在。我们添加如下:

 

{
    "name": "Python: Django",
    "type": "python",
    "request": "launch",
    "program": "${workspaceFolder}/manage.py",
    "console": "integratedTerminal",
    "args": [
        "runserver",
        "--noreload"
    ],
    "django": true
},

 

其中"django": true告诉VSCode开启Django页面模板调试功能。

3. 点击Debug > Start Debugging按钮,浏览器中打开URL http://127.0.0.1:8000/将可以看到我们的APP顺利的跑起来了。

 其实任何时候感觉想要调试一下应用效果时,我们都可以用Debug来启动服务,此外这个操作还会自动保存所有打开着的文件。

这样就不用每次都到命令行敲一遍启动命令,倍爽有木有!!!

4. Debug不仅仅只有启动和保存功能,我们下面通过具体案例来体验下高级用法。

  先码代码

  • hello/urls.py:添加访问路由到urlpatterns list中
path("hello/<name>", views.hello_there, name="hello_there"),

 

  • hello/views.py
import re
from datetime import datetime
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, Django!")

def hello_there(request, name):
    now = datetime.now()
    formatted_now = now.strftime("%A, %d %B, %Y at %X")

    # Filter the name argument to letters only using regular expressions. URL arguments
    # can contain arbitrary text, so we restrict to safe characters only.
    match_object = re.match("[a-zA-Z]+", name)

    if match_object:
        clean_name = match_object.group(0)
    else:
        clean_name = "Friend"

    content = "Hello there, " + clean_name + "! It's " + formatted_now
    return HttpResponse(content)

5. 在Debug中设定断点(breakpoints)于now = datetime.now() 所在行。

 

 

 6. 按F5或Debug > Start Debugging 开启调试,VSCode顶部将会出现一个如下的Debug工具栏。

Pause (or Continue, F5), Step Over (F10), Step Into (F11), Step Out (Shift+F11), Restart (Ctrl+Shift+F5), and Stop (Shift+F5). See VS Code debugging for a description of each command.

 

 

 7. 在下面的终端中也会出现相关的控制信息。通过浏览器打开URL http://127.0.0.1:8000/hello/VSCode, 在页面渲染完成前,VSCode会暂停在设定的断点处。黄色小箭头代表其是即将执行到的下一行。

 

 

 点击 Step Over(F10) 执行 now = datetime.now()所在行。

在左边Debug菜单栏我们将会看到很多实时输入信息,包含运行时的变量值等等。我们可以在这里检查各个赋值或相关信息是否符合设计目标。

 

 

 程序暂停在断点位置时,我们可以回到代码中更改相关语句,调试器中的相关输入信息也会实时做状态更新。我们可以尝试将formatted_now的赋值做如下更改,用来直观地比较查看下调试器状态更新。

now.strftime("%a, %d %B, %Y at %X")
'Fri, 07 September, 2018 at 07:46:32'
now.strftime("%a, %d %b, %Y at %X")
'Fri, 07 Sep, 2018 at 07:46:32'
now.strftime("%a, %d %b, %y at %X")
'Fri, 07 Sep, 18 at 07:46:32'

 

 

我们可以按F5逐行执行接下来的语句,并观察调试器输出信息,直到最终应用页面完全渲染完成,点选Debug > Stop Debugging 或 command (Shift+F5)关闭调试。

 

  0x5 - Go to Definition

VSCode也支持查看函数和类的定义查看:

  • Go to Definition jumps from your code into the code that defines an object. For example, in views.py, right-click on HttpResponse in the home function and select Go to Definition (or use F12), which navigates to the class definition in the Django library.

  • Peek Definition (Alt+F12, also on the right-click context menu), is similar, but displays the class definition directly in the editor (making space in the editor window to avoid obscuring any code). Press Escape to close the Peek window or use the x in the upper right corner.

 

 

 

0x6 - Template, Static, Models编程

接下来可以在模板,静态文件和数据处理的功能编程实现上实践上面介绍的这些功能,练习整个集成开发环境的操作熟练度。

其实如果有一定基础的话,我相信一天你就将会从入门到精通。

详细的代码个实现步骤在这里就不在继续往下贴了。详细教程大家可按这个链接中的内容参照实现。

https://code.visualstudio.com/docs/python/tutorial-django#_create-multiple-templates-that-extend-a-base-template

 

0x7 - 问题分享

整个过程中只有遇到的问题:

1. VSCode无法原生支持Django Models相关对象的关联检查。

我们需要额外做点工作:

  • ctrl+shift+`(ESC下面那个键)打开命令终端,不用手工敲任何命令,终端会自动切换和激活到对应的虚拟开发环境。

安装pylint-django

 

  •  然后进入VSCode setting里面设定pylint参数,具体如下:

 

就这样,问题解决!

 

 

==========================================================

由于还有繁重的日常工作要忙,这篇文章历时了几天时间断断续续整理出来,也精简了不少官方指导中的文字描述。可能会对各位阅读和操作来带一些困扰,所以还是建议各位直接去读官方文档。我们这里主要是集中整理了下Anaconda和VSCode的集成开发环境配置,以备未来不时之需,若能顺便帮到任何人,将倍感欣慰。各位若有任何问题,欢迎提出,我将会汇整日后自己或其他来源收集到的问题陆续补充到0x7。

 

最后,希望大家能多多动手

多多敲代码

多多点赞

多多分享

 

回家遛女儿去咯

Over~~

 

 

Guess you like

Origin www.cnblogs.com/chilliegg/p/11920751.html