使用VSCode+Python+Djagon快速搭建Restful Web Application

行动起来才是最重要的

因工作需要,这几天接触了Python,需要使用Python语言来构建一个后端服务,提供HTTP Restful API给前端访问。由于之前完全没有接触过Python,所以在准备开发环境时花了一些时间,不过好在最终还是顺利的让程序运行起来了。我想用这篇文章记录下如何从零到一的搭建整个Python WEB环境,希望能够帮助Python新手轻松开启Python的WEB开发之旅。

个人的感受,如果你想学习一门编程语言,最好的就是带着目的去学习,比如你想学习Python,那你首先要知道你为什么学习它,你是想写爬虫程序来获得互联网上的数据?还是想从事AI编程,想基于TensorFlow, Pytorch库来开启自己的机器学习之旅?清晰的目标是你行动的唯一驱动力,没有目标,你很可能会在学习的过程中放弃,因为会遇到各种不同的问题。

Python WEB环境搭建的整体流程

想要在本地搭建Python的WEB开发环境,整体的流程其实和其它的编程语言也一样,无非以下几个大的步骤:

  • 安装运行时环境
  • 配置环境变量
  • 安装依赖管理工具
  • 基于某个框架开发
  • 在IDE里开发和调试

安装Python运行时环境

  • 常规的安装方式,下载Python安装文件进行安装(新手推荐
    Python 针对不同的操作系统都提供了相应的binary Installer(可执行安装文件),点击下方链接进入下载页面直接下载即可。
    Python下载
    DownLoad Python Installer
    例如我目前使用的是Mac电脑,进入下载页面,官网会识别到我的操作系统,直接提供了适应于MacOS的.pkg安装文件,我们直接下载就可以安装了。

如果想安装其它版本的Python,可以点击对应的操作系统名称进入相应的下载页面。比如:【MacOS 安装文件下载页

  • 通过安装工具进行安装
    在MacOS上,可以通过Homebrew工具来安装最新版本的Python。
#如果没有安装过Homebrew,可以使用下面的命令来安装.
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

#如果已经安装了Homebrew,则直接使用brew命令来安装Python.
brew install python

此外,如果要在开发电脑上安装多个Python版本,则需要用到 pyenv 这个工具来管理多个Python版本了,如果大家有需要,后面我们会专门写一篇文章来讲解pyenv如何管理多版本。

  • 通过源代码编译安装(不推荐
    大体的过程如下,但不同的操作系统环境可能还会遇到不同的问题,所以整体的过程会比较复杂且多变,不推荐新手通过这种方式来安装。
#安装依赖库
brew install openssl readline sqlite3 xz zlib wget

#下载源代码
wget https://www.python.org/ftp/python/3.9.6/Python-3.9.6.tgz

#解压缩 
tar -xvzf Python-3.9.6.tgz
cd Python-3.9.6

#进行编译配置
./configure --prefix=$HOME/.localpython/python-3.9.6 --with-openssl=$(brew --prefix openssl) --enable-optimizations

#编译安装
make -j $(nproc)
make install

配置环境变量

Python不需要过多的环境变量,主要是将Python3(也就是Python解释器)的可执行文件路径加入到PATH这个系统环境变量里。如果是通过Installer安装的,安装器会默认帮大家设置好PATH,所以在安装完Python之后可以先验证一下。

#查看python3 版本,注意:Python3的可执行文件是python3.
#有些操作系统可能自带了Python2, Python2的可执行文件是python
python3 --version
Python 3.11.9

如果可以正常看到版本号,那我们的Python就已经安装好了。

安装依赖管理工具: 【 pipenv 】

pipenv 是一个用于管理 Python 项目依赖和虚拟环境的工具,它结合了 pip 和 virtualenv 的功能,以提供更方便和一致的开发环境。pipenv 旨在简化 Python 项目依赖的管理,使得创建和管理虚拟环境更加简单,并且提供了锁定依赖版本的功能,以确保项目在不同环境中的一致性。

主要功能和优点

  • 虚拟环境管理:
    自动为每个项目创建和管理独立的虚拟环境,无需手动创建和激活。
    通过 pipenv shell 命令可以轻松进入项目的虚拟环境。
  • 依赖管理:
    使用 Pipfile 和 Pipfile.lock 文件来管理项目的依赖。
    Pipfile 列出项目的直接依赖,而 Pipfile.lock 则锁定所有依赖的确切版本,以确保一致的依赖环境。
  • 集成依赖安装:
    使用 pipenv install 来安装依赖,同时更新 Pipfile 和 Pipfile.lock。
    支持开发依赖和生产依赖的分离管理(使用 --dev 选项)。
  • 安全性检查:
    内置安全性检查功能,通过 pipenv check 命令可以检查已安装依赖的安全性漏洞。

PS: 我们可以将pipenv当作是Python版的 Maven或者Gradle。

#执行如下命令可安装pipenv
python3 -m pip install pipenv

#将pipenv所在目录加入PATH环境变量
#假如是安装在/usr/local/bin下,总之找到pipenv所在的位置
export PATH=/usr/local/bin:$PATH

安装Django开发套件

当我们安装好了pipenv后,就可以通过pipenv来管理依赖项了。如果想通过Python来开发WEB API,Django + DjangoRestFramework是一个不错的选择。我们先安装这两个依赖库。

  • Step1、准备工作目录
#先在当前用户目录下创建一个文件夹,作为web项目的根目录
mkdir ~/web-application
cd ~/web-application

  • Step2、初始化Python虚拟环境
#在当前目录初始化Python虚拟环境
pipenv --python 3.11.9

====================================================================================================
txzq1899@MacbookPro [09:24:40] [~/web-application]
-> % pipenv --python 3.11.9
Creating a virtualenv for this project...
Pipfile: /Users/txzq1899/web-application/Pipfile
Using /usr/local/bin/python3 (3.11.9) to create virtualenv...
⠙ Creating virtual environment...created virtual environment CPython3.11.9.final.0-64 in 485ms
  creator CPython3Posix(dest=/Users/txzq1899/.local/share/virtualenvs/web-application-d61xTGkA, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/txzq1899/Library/Application Support/virtualenv)
    added seed packages: pip==24.0, setuptools==69.5.1, wheel==0.43.0
  activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator

✔ Successfully created virtual environment!
Virtualenv location: /Users/txzq1899/.local/share/virtualenvs/web-application-d61xTGkA
Creating a Pipfile for this project...
  • Step3、检查虚拟Pipfile

#我们可以看到会创建一个Pipfile
txzq1899@MacbookPro [08:26:28] [~/web-application]
-> % ll
total 8
drwxr-xr-x   3 txzq1899  staff    96  5 23 09:25 ./
drwxr-x---+ 50 txzq1899  staff  1600  5 23 09:28 ../
-rw-r--r--   1 txzq1899  staff   170  5 23 09:25 Pipfile

#查看Pipfile的内容
txzq1899@MacbookPro [09:28:12] [~/web-application]
-> % cat Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]

[dev-packages]

[requires]
python_version = "3.11"
python_full_version = "3.11.9"

  • Step4、激动虚拟环境
#激动虚拟环境
pipenv shell
==================================================

txzq1899@MacbookPro [09:32:18] [~/web-application]
-> % pipenv shell
Launching subshell in virtual environment...
 . /Users/txzq1899/.local/share/virtualenvs/web-application-d61xTGkA/bin/activate

txzq1899@MacbookPro [09:32:22] [~/web-application]
-> %  . /Users/txzq1899/.local/share/virtualenvs/web-application-d61xTGkA/bin/activate

#看到这对小括号和当前目录名,就表示已经在虚拟环境下了
(web-application)
txzq1899@MacbookPro [09:32:22] [~/web-application]
-> %
  • Step5、安装Django依赖
#安装django依赖
pipenv install 'django>=5.0.2,<6'
==================================================

(web-application)
txzq1899@MacbookPro [09:32:22] [~/web-application]
-> % pipenv install 'django>=5.0.2,<6'
Installing django>=5.0.2,<6...
Resolving django>=5.0.2,<6...
Added django to Pipfile's [packages] ...
✔ Installation Succeeded
Pipfile.lock not found, creating...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Locking [dev-packages] dependencies...
Updated Pipfile.lock (375722098e27a39dca8aa8f402a76846e36fbfffc7c61abbba12bbc636301d74)!
Installing dependencies from Pipfile.lock (301d74)...
(web-application)
txzq1899@MacbookPro [09:35:36] [~/web-application]
  • Step6、安装DjangoRestFramework依赖
pipenv install 'djangorestframework>=3.14.0, <4'

==================================================
-> % pipenv install 'djangorestframework>=3.14.0, <4'
Installing djangorestframework>=3.14.0, <4...
Resolving djangorestframework>=3.14.0, <4...
Added djangorestframework to Pipfile's [packages] ...
✔ Installation Succeeded
Pipfile.lock (301d74) out of date, updating to (14a156)...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Locking [dev-packages] dependencies...
Updated Pipfile.lock (a258261403332d017e3d6b6f8e07a5adea4463c633791657290167e03e14a156)!
Installing dependencies from Pipfile.lock (14a156)...
(web-application)
txzq1899@MacbookPro [09:44:44] [~/web-application]
-> %

初始化Django项目

前面的准备工作做好之后,就可以创建一个Django项目了。
django提供了类似于spring initializer 这样的脚手架创建工具:django-admin

初始化Django工程

django-admin startproject hello_world

==================================================
-> % django-admin startproject hello_world
(web-application)
txzq1899@MacbookPro [10:33:16] [~/web-application]

-> % ll
total 16
drwxr-xr-x   5 txzq1899  staff   160  5 23 10:33 ./
drwxr-x---+ 50 txzq1899  staff  1600  5 23 10:33 ../
-rw-r--r--   1 txzq1899  staff   228  5 23 09:43 Pipfile
-rw-r--r--   1 txzq1899  staff  1915  5 23 09:44 Pipfile.lock
drwxr-xr-x   4 txzq1899  staff   128  5 23 10:33 hello_world/
(web-application)
txzq1899@MacbookPro [10:33:26] [~/web-application]
#hello-world初始化工程如下:
-> % tree
.
├── Pipfile
├── Pipfile.lock
└── hello_world
    ├── hello_world
    │   ├── __init__.py
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    └── manage.py

3 directories, 8 files

初次启动

脚手架工程初始化后,就要以尝试启动该WEB应用了。
通过python manage.py runserver 来启动WEB应用。

#首先需要进入hello-world目录
cd hello-world

#启动server,监听8088端口
python manage.py runserver 8088

==================================================
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 23, 2024 - 02:38:28
Django version 5.0.6, using settings 'hello_world.settings'
Starting development server at http://127.0.0.1:8088/
Quit the server with CONTROL-C.

^C%
(web-application)
txzq1899@MacbookPro [10:38:42] [~/web-application/hello_world]

我们可以看到第一次运行,会提示有【18】个没有运应的迁移,需要我们执行migrate命令,这里有一个概念:Migration,这是django 框架的一个重要概念,这里先不展开讨论,大家先记住有这么个概念就可以了。

执行迁移命令

python manage.py migrate
==================================================

(web-application)
txzq1899@MacbookPro [10:49:02] [~/web-application/hello_world]
-> % python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK
(web-application)
txzq1899@MacbookPro [10:49:02] [~/web-application/hello_world]
-> % 

启动Django WEB应用

#首先需要进入hello-world目录
cd hello-world

#启动server,监听8088端口
python manage.py runserver 8088
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
May 23, 2024 - 02:51:56
Django version 5.0.6, using settings 'hello_world.settings'
Starting development server at http://127.0.0.1:8088/
Quit the server with CONTROL-C.
==================================================

创建超级用户

#通过createsuperuser命令来创建管理员用户
python manage.py createsuperuser
==================================================

-> % python manage.py createsuperuser
Username (leave blank to use 'txzq1899'):
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.
(web-application)
txzq1899@MacbookPro [10:55:21] [~/web-application/hello_world]
-> %

访问WEB 应用

打开浏览器,访问:http://localhost:8088

django 启动成功

访问http://localhost:8088/admin
admin 登录
成功登录后:
管理页

在VisualStudioCode中打开Django工程

初始化完后,我们就可以使用VSCode打开Django工程了。此外我们也需要在VSCode中安装Python开发插件

  • 安装Python Extension Pack
    安装 Python Extension Pack

  • 打开web-application文件夹
    在这里插入图片描述

  • 配置Python解释器
    按住:command + shift + P
    选择解释器
    这里我们一定要选择由Pipenv管理的虚拟环境所指向的解释器。
    选择Pipenv管理的解释器

新增模块和API

当我们验证了Django WEB服务启动没有问题后,我们就开始编写第一个API接口了。
首先我们先新增一个模块:hello

  • 新增模块
python manage.py startapp hello
==================================================

txzq1899@MacbookPro [13:45:45] [~/web-application/hello_world]
-> % python manage.py startapp hello
(web-application)
txzq1899@MacbookPro [13:46:00] [~/web-application/hello_world]
-> % ll

#Django会帮我们自动创建hello模块以及基础代码
total 400
drwxr-xr-x  7 txzq1899  staff     224  5 23 13:46 ./
drwxr-xr-x  5 txzq1899  staff     160  5 23 10:33 ../
-rw-r--r--  1 txzq1899  staff   69161  5 23 11:11 abc.txt
-rw-r--r--  1 txzq1899  staff  131072  5 23 11:05 db.sqlite3
drwxr-xr-x  9 txzq1899  staff     288  5 23 13:46 hello/
drwxr-xr-x  7 txzq1899  staff     224  5 23 10:33 hello_world/
-rwxr-xr-x  1 txzq1899  staff     667  5 23 10:33 manage.py*
(web-application)
txzq1899@MacbookPro [13:46:03] [~/web-application/hello_world]
-> % tree
.
├── abc.txt
├── db.sqlite3
├── hello
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── hello_world
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

4 directories, 15 files
(web-application)
txzq1899@MacbookPro [13:46:32] [~/web-application/hello_world]
  • 新增API
    我们在hello模块的views.py中新中一个方法
    def say_hello(request):
        return HttpResponse("Hello world!")
    
    然后在hello模块的urls.py中增加context path 映射
    #先引用views
    from . import views
    
    urlpatterns = [
    	path('hello', views.say_hello, name='hi'),
    ]
    
    接着在hello_world的settings.py中将hello应用添加进INSTALLED_APPS中
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        #新增下边这一行
        'hello',
    ]
    
    最后我们在hello_world中的urls.py中include新增模块的urls
    urlpatterns = [
        path('admin/', admin.site.urls),
        #新增下边这一行
        path('', include('hello.urls')),
    ]
    

在VSCode下启动和调试WEB应用

  • 在.vscode目录下新建launch.json文件,文件内容如下

    {
          
          
        // 使用 IntelliSense 了解相关属性。 
        // 悬停以查看现有属性的描述。
        // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
        "version": "0.2.0",
        "configurations": [
            {
          
          
                "name": "Python 调试程序: Django",
                "type": "debugpy",
                "request": "launch",
                "args": [
                    "runserver"
                ],
                "django": true,
                "autoStartBrowser": false,
                "program": "${workspaceFolder}/hello_world/manage.py"
            }
        ]
    }
    
  • 进入调试页面
    VSCode 调试窗口

  • 启动调试
    我们可以看到启动后,端口号为8000
    启动调试

  • 访问API
    打开浏览器,访问:http://localhost:8000/hello
    测试hello-api

一切准备就绪

到这里我们使用Python + Django + VSCode的WEB开发环境基本上就准备就绪了,希望这篇文章可以给同样是Python新手的你带来帮助。

关注我的公众号

欢迎大家关注、点赞、转发,一起交流软件开发、架构设计、云原生技术。
TXZQ聊IT技术与架构

猜你喜欢

转载自blog.csdn.net/u011278722/article/details/139079354