Django学习笔记(一)

来源:互联网 发布:squid 默认端口 编辑:程序博客网 时间:2024/05/22 05:57

Django学习笔记(一)


前言

小胖最近在学习Python web开发,Django作为Python web框架中最具有代表性的框架肯定是第一选择。于是小胖便参照Django的官方教程来学习Django,期间会将学习到的一些知识点整理记录到Django的学习笔记中。这会是一篇基础的使用教程,欢迎大家一起学习交流讨论。有兴趣的童鞋可以参考Django官方教程文档。


venv创建虚拟环境

在构建Python项目之前一般都会构建一个虚拟环境用来安装项目所需的Python包,常用的虚拟环境一般是virtualenv。在Python3.3里已经内置了venv模块支持虚拟环境。venv模块支持创建”轻量级”虚拟环境,提供与系统Python的隔离支持。这里小胖将会使用venv来构建虚拟环境。

在当前目录下创建虚拟环境

python -m venv .

“venv”参数详细

PS E:\code\test> python -m venv -husage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]            [--upgrade] [--without-pip] [--prompt PROMPT]            ENV_DIR [ENV_DIR ...]Creates virtual Python environments in one or more target directories.positional arguments:  ENV_DIR               A directory to create the environment in.optional arguments:  -h, --help            show this help message and exit  --system-site-packages                        Give the virtual environment access to the system                        site-packages dir.  --symlinks            Try to use symlinks rather than copies, when symlinks                        are not the default for the platform.  --copies              Try to use copies rather than symlinks, even when                        symlinks are the default for the platform.  --clear               Delete the contents of the environment directory if it                        already exists, before environment creation.  --upgrade             Upgrade the environment directory to use this version                        of Python, assuming Python has been upgraded in-place.  --without-pip         Skips installing or upgrading pip in the virtual                        environment (pip is bootstrapped by default)  --prompt PROMPT       Provides an alternative prompt prefix for this                        environment.Once an environment has been created, you may wish to activate it, e.g. bysourcing an activate script in its bin directory.

一般使用我们可以加上”–system-site-packages”参数使虚拟环境支持使用全局Python包。

激活虚拟环境

Posix标准平台下:$ source <venv>/bin/activateWindows cmd:C:> <venv>/Scripts/activate.batWindows PowerShell:PS C:> <venv>/Scripts/Activate.ps1

PowerShell激活环境失败解决方法

小胖是在windows平台开发的,在通过PowerShell激活虚拟环境时遇到以下问题:

PS E:\code\test> Scripts/Activate.ps1Scripts/Activate.ps1 : 无法加载文件 E:\code\test\Scripts\Activate.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。所在位置 行:1 字符: 1+ Scripts/Activate.ps1+ ~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : SecurityError: (:) [],PSSecurityException    + FullyQualifiedErrorId : UnauthorizedAccess

遇到上面情况修改执行策略就可以了:

PS E:\code\test> set-executionpolicy remotesigned执行策略更改执行策略可帮助你防止执行不信任的脚本。更改执行策略可能会产生安全风险,如 http://go.microsoft.com/fwlink/?LinkID=135170中的 about_Execution_Policies 帮助主题所述。是否要更改执行策略?[Y] 是(Y)  [A] 全是(A)  [N] 否(N)  [L] 全否(L)  [S] 暂停(S)  [?] 帮助 (默认值为“N”): y

然后虚拟环境便可以被激活了。环境问题解决了,接下来我们就可以安装Django了。

 PS E:\code\test> Scripts/Activate.ps1(test) PS E:\code\test>

安装Django

最简单的方法就是通过pip进行安装,安装的时候可以使用国内镜像加速安装,下面列出两个常用镜像:

  • 豆瓣:http://pypi.douban.com/simple/
  • 清华:https://pypi.tuna.tsinghua.edu.cn/simple

安装Django:

 pip install Django -i http://pypi.douban.com/simple/

验证Django是否安装成功,首先先进入Python的交互环境:

(test) PS E:\code\test> pythonPython 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import django>>> print(django.get_version())1.11.4

创建Django项目

Django内置了脚手架工具,通过脚手架命令可以很快地构建一个Django项目。

(test) PS E:\code\test> django-admin startproject mysite

进入mysite目录可以看到如下目录结构:

mysite/    manage.py    mysite/        __init__.py        settings.py        urls.py        wsgi.py
  • mysite文件夹是项目的根目录,开发者可以进行重命名。
  • manage.py是命令行文件用于与Django项目交互。
  • 里层的mysite文件夹就是实际的Python包,可以同过这个名字引入Python文件(例如:mysite.urls)。
  • mysite/init.py:一个空文件用来告诉Python这是一个Python包。
  • mysite/settings.py:配置文件。
  • mysite/urls.py:路由文件。
  • mysite/wsgi.py:web服务器入口。

以上简单翻译自官方教学文档,有兴趣了解的童鞋可以自己查看原文。

运行Django项目

项目创建完成了,接下来我们可以使用Django内置的开发服务器跑一下项目看看:

(test) PS E:\code\test\mysite> python manage.py runserver 8080Performing system checks...System check identified no issues (0 silenced).You have 13 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.September 03, 2017 - 17:58:25Django version 1.11.4, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8080/Quit the server with CTRL-BREAK.

开发服务器默认是8000端口,开发时要注意端口是否被占用。小胖在运行服务时报错,发现酷狗音乐会占用8000端口,所以改用8080端口。出现以上输出信息的时候就说明项目已经成功启动就可以了,可以打开浏览器输入http://127.0.0.1:8080/查看效果。一般情况下服务器会自动加载修改后的Python代码,所以不需要每次重新启动服务器。
好了现在项目已经搭建完成,接下来小胖会根据教程编写一个调查问卷的网站,敬请期待。

原创粉丝点击