构建您的第一个Python和Django应用程序

2017-08-16

构建您的第一个Python和Django应用程序

你以前可能听说过Python,特别是如果你已经编码了一段时间。

如果没有,Python是一种高级别的通用编程语言。这意味着您可以使用它来编写从简单的游戏到每月支持数百万用户的网站。

事实上,几个具有数百万访问者的高调网站依赖于Python的一些服务。示例包括YouTubeDropbox

话虽如此,为什么要首先使用Python?为什么不像Ruby或PHP那样在野外像许多其他流行的语言一样?那么,使用Python可以获得以下好处:

  1. 易读的语法。
  2. 活跃的开源社区。
  3. 容易学习
  4. Python可用于从基本的类shell脚本到高级的Web开发等各种工作。

不适合使用Python

虽然您可以使用诸如wxPython之类的工具轻松地编写一个使用Python的桌面应用程序,但您通常会更好地使用您在Windows上定位的平台所提供的专门工具,例如.NET。

当您的特定用例具有非常专业化的要求时,您也应该不要使用Python,这些要求更好地被其他语言所理解。一个例子是当您构建一个嵌入式系统时,C,C ++和Java等语言主导的领域。

Python2 VS Python3

Python 2.7.x和3.x都在广泛使用。Python 3引入了对Python 2编写的应用程序的更改,以便重新编写Python 3x分支。然而,您将需要使用的大多数库现在已经移植到Python 3。

本教程将在编写本文时使用3.6.1版的Python 3。原则保持不变,只需要稍微的语法修改才能使代码在Python 2.7.x下运行。

一些Python代码示例

Hello World

如前所述,Python的主要优点之一是它非常容易读取的语法。多么容易查看Python的无处不在的版本Hello World

# This line of code will print "Hello, World!" to your terminal
print("Hello, World!")

此代码打印Hello, World!到控制台。您可以通过访问此网站轻松地尝试此代码,将代码示例粘贴在页面右侧的编辑器中,然后单击run页面上方的按钮以查看输出。

条件逻辑

条件逻辑也是一样简单。以下是一些代码,用于检查用户的年龄是否超过18岁,如果是,则打印Access allowed或Access not allowed以其他方式

# read in age
age = int(input("What's your age?"))

if age >= 18:
    print("Access allowed")
elif age < 18 and age > 0:
    print("Access not allowed")
else:
    print("Invalid age")

该input()功能用于读取键盘输入。因此,您需要在运行脚本以在脚本的其余部分执行后,在终端提示符中键入某些内容。请注意,input()函数被包装在int()函数中。

这是因为input()读取价值观strings,但我们需要年龄成为integer。因此,我们必须将键盘输入转换为字符串,否则我们将在检查字符串是否大于18时会得到一个错误。

最后,请注意else对于不符合在if语句中被检查的条件的任何其他输入执行的语句。

抽象数据类型

Python还具有一些优秀的内置抽象数据类型,用于保存项目集合。一个例子是可以用来保存任何类型变量的列表。以下代码显示了如何创建列表并对其进行迭代,以将每个项目打印到终端。

# create a list called my_list
my_list = [1, 2, 3, "python", 67,  [4, 5]]

# go through my_list and print every item
for item in my_list:
    print item

上面的代码创建了一个包含数字,字符串和列表的列表(是的,列表可以包含其他列表!)。为了迭代列表,for-in循环很方便。记住,列表是零索引的,所以我们也可以使用索引访问列表项。例如,要输出字符串python,可以写:

# create a list called my_list
my_list = [1, 2, 3, "python", 67,  [4, 5]]

print(my_list[3])

字典

Python提供的另一个优秀的数据类型是开箱即用的字典。字典存储键值对,类似于JSON对象。创建字典也很简单。

# create a dictionary
person = {
            "name": "Amos",
            "age": 23,
            "hobbies": ["Travelling", "Swimming", "Coding", "Music"]
        }

# iterate through the dict and print the keys
for key in person:
    print(key)

# iterate through the dict's keys and print their values
for key in person:
    print(person[key])

现在你知道一点Python,让我们来谈谈Django。

Django

Django是一个Python Web框架。 自2005年以来一直是免费的和开源的。它非常健壮,并附有优秀的文档和常用web开发的功能。它提供的一些优秀工具是:

  1. 优秀的轻量级服务器用于开发和测试
  2. 良好的模板语言
  3. CSRF等安全功能包括在内。

Django中包含了许多其他有用的东西,但是您可能会发现它们。我们将在本教程中使用Django构建我们的网站。

安装

在本教程中,我将向您展示如何让Django网站启动并运行。在我们到达那里之前,首先从Python网站获取最新的Python的副本。

请注意,如果您使用的是OSX,并且您已经安装了Homebrew,那么可以使用 brew install 来安装 Python

$ brew install python3

之后,直奔那一Getting started with Django节

为您的操作系统安装正确的版本后,您需要确保其设置正确。打开一个终端并输入:

$ python3

您应该看到类似于以下内容的内容:

Python 3.6.1 (default, Apr  4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

这是交互式的Python shell。CTRL + D现在点击退出

配置虚拟环境

为了避免使用不必要的软件包污染我们的系统环境,我们将使用虚拟环境来存储我们的软件包。virtualenv 是一个优秀的虚拟环境管理软件,并且可以免费使用。我们将使用Python的软件包管理器pip来安装我们以后需要的Django等软件包。首先,我们来virtualenv安装。

$ pip install virtualenv

安装完成,创建一个名为 project 的文件夹,然后 cd project。

$ mkdir projects
$ cd projects

进入 projects 文件夹,创建一个名为 hello 的文件夹。我们的应用将在这个文件下创建

$ mkdir hello

我们将要在 hello 文件夹中, 创建我们需要的开发环境。

$ virtualenv -p /usr/local/bin/python3 env

这里 -p 是指定您想在虚拟环境中使用的 Python 版本。当然,也可以制定其他的 python 版本。 env 是虚拟环境的名称,您也可以将其改为更符合项目名称或者其他内容。

一旦完成,你应该有一个文件夹中envhello文件夹。你的结构现在应该是这样的。

projects
├─hello
│   ├── env

您现在可以激活虚拟环境并开始编码!

$ source env/bin/activate

您将看到带有环境名称的提示符。这意味着环境是活跃的。

$  (env)

安装Django

这是一个简单的点安装。最新的Django版本是Django 1.11.4 LTS

$ pip install django

创建应用程序

现在安装了Django,我们可以使用它的起始脚本来创建一个框架项目。这就像使用其管理脚本一样简单。

$ django-admin startproject helloapp

运行此命令创建一个具有以下结构的骨架django应用程序:

helloapp
├─helloapp
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

当您查看helloapp创建的文件夹时,将会找到一个名为“ manage.py另一个文件夹”的文件helloapp。这是您的主要项目文件夹,并且包含名为文件的项目的设置以及文件settings.py中项目中的路由urls.py。随意打开settings.py文件,以熟悉其内容。

赞,准备继续前进?

更改应用设置

让我们改变一些设置。settings.py在您最喜欢的编辑器中打开文件。找到一个名为Installed Apps的部分,看起来像这样。

# helloapp/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Django运用于应用程序的概念。应用程序是一个独立的代码单元,可以自行执行。应用程序可以执行许多操作,例如在浏览器上投放网页或处理用户验证或任何其他可以想到的内容。Django附带预先安装的一些默认应用程序,如身份验证和会话管理器应用程序。我们将创建的任何应用程序或我们将需要的第三方应用程序将Installed Apps在默认应用程序安装后添加到列表的底部。

在创建自定义应用程序之前,让我们更改应用程序时区。Django使用tz database时区,可以在这里找到列表。

时区设置看起来像这样

# helloapp/settings.py
TIME_ZONE = 'UTC'

将其更改为适合您的时区的类似的东西。

# helloapp/settings.py
TIME_ZONE = 'Asia/Shanghai'

创建自己的应用程序

重要的是要注意,Django应用程序遵循模型,视图,模板范例。简而言之,应用程序从模型获取数据,该视图对数据执行某些操作,然后渲染包含处理信息的模板。因此,Django模板对应于传统MVC中的视图,Django视图可以与传统MVC中的控制器相似。

话虽如此,让我们创建一个应用程序。cd进入第一个helloapp文件夹并输入;

$ python manage.py startapp howdy

运行此命令将创建一个名为howdy的应用程序。您的文件结构应该看起来像这样。

helloapp
├── helloapp
│        ├── __init__.py
│        ├── settings.py
│        ├── urls.py
│        └── wsgi.py
├── howdy
│        ├── __init__.py
│        ├── admin.py
│        ├── apps.py
│        ├── migrations
│        ├── models.py
│        ├── tests.py
│        └── views.py
└── manage.py

要让Django认识我们的全新应用,我们需要将应用名称添加到Installed Apps我们的settings.py文件列表中。

# helloapp/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'howdy'
]

一旦完成,我们来运行我们的服务器,看看会输出什么。我们提到Django配有一个内置的轻量级Web服务器,它在开发过程中很有用,在生产中不应该使用。运行服务器如下:

$ python manage.py runserver

您的输出应类似于以下内容:

$ Performing system checks...

System check identified no issues (0 silenced).

You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.

June 04, 2017 - 10:42:08
Django version 1.11.4, using settings 'helloapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

如果你仔细看,你会看到一个警告,你在有启动server前,没有执行 migrate。忽略现在。转到您的浏览器并访问http://127.0.0.1:8000/。如果所有运行顺利,您应该看到Django欢迎页面。 django 我们将用我们自己的模板替换这个页面。但首先,我们来谈谈 migrations。

Migrations

Migrations 使您可以轻松更改数据库模式(模型),而不必丢失任何数据。任何时候创建新的数据库模型,运行迁移将更新您的数据库表以使用新的架构,而不必丢失任何数据,或者经历繁琐的删除和重新创建数据库的过程。

Django附带了一些已经为其默认应用程序创建的迁移。如果您的服务器仍在运行,请通过点击来停止CTRL + C。通过键入以应用迁移:

$ python manage.py migrate

如果成功,您将看到类似于此的输出。

Operations to perform:
  Apply all migrations: sessions, auth, contenttypes, admin
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... 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 sessions.0001_initial... OK

现在运行服务器不会显示任何警告。

网址和模板

当我们运行服务器时,会显示默认的Django页面。howdy当有人访问主页网址时,我们需要Django访问我们的应用程序/。为此,我们需要定义一个URL来告诉Django在哪里查找主页模板。

打开urls.py内部helloapp文件夹中的文件。应该看起来像这样。

 # helloapp/urls.py
 """helloapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:

https://docs.djangoproject.com/en/1.9/topics/http/urls/

Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

您可以看到,Django管理网站存在一个现有的URL模式,默认情况下与Django配合使用。我们添加自己的url来指向我们的howdy应用程序。编辑文件看起来像这样。

# helloapp/urls.py
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('howdy.urls')),
]

请注意,我们已经include从django.conf.urls添加了一个导入,并为空路由添加了一个url模式。有人访问主页(在我们的例子中是http:// localhost:8000),Django会在howdy应用程序中寻找更多的url定义。由于没有,运行应用程序将产生一个巨大的堆栈跟踪由于ImportError。

.
.
ImportError: No module named 'howdy.urls'

我们来解决这个问题。转到howdy应用程序文件夹并创建一个名为urls.py。该howdy应用程序文件夹现在应该是这样的。

├── howdy
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py

在新urls.py文件里面写这个。

# howdy/urls.py
from django.conf.urls import url
from howdy import views

urlpatterns = [
    url(r'^$', views.HomePageView.as_view()),
]

此代码从我们的howdy应用程序导入视图,并希望HomePageView定义一个被调用的视图。由于我们没有,请views.py在howdy应用程序中打开文件并编写此代码。

 # howdy/views.py
from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.
class HomePageView(TemplateView):
    def get(self, request, **kwargs):
        return render(request, 'index.html', context=None)

该文件定义了一个调用的视图HomePageView。Django视图进行request并返回response。在我们的例子中,该方法get希望对我们urls.py文件中定义的URL进行HTTP GET请求。在旁注中,我们可以重命名我们的方法post来处理HTTP POST请求。

一旦接收到HTTP GET请求,该方法将呈现一个称为index.html该模板的模板,它只是一个普通的HTML文件,它可以将正常的HTML标签与特定的Django模板标签一起编写。如果现在运行服务器,您将看到以下错误页面: server error 这是因为我们根本没有任何模板!Django在templates应用程序中的文件夹中查找模板,以便在howdy应用程序文件夹中创建一个模板。

$ mkdir templates

进入刚刚创建的模板文件夹,并创建一个名为 index.html

(env) hello/helloapp/howdy/templates
 > touch index.html

在index.html文件内部,粘贴此代码。

<!-- howdy/templates/index.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Howdy!</title>
    </head>
    <body>
        <h1>Howdy! I am Learning Django!</h1>
    </body>
</html>

现在运行你的服务器。

$ python manage.py runserver

你应该看到你的模板渲染。 home page

链接页面

让我们再添加一个页面。在您的howdy/templates文件夹中,添加一个名为about.html。在里面写这个HTML代码:

<!-- howdy/templates/about.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Howdy!</title>
    </head>
    <body>
        <h1>Welcome to the about page</h1>
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc quis neque ex. Donec feugiat egestas dictum. In eget erat sit amet elit pellentesque convallis nec vitae turpis. Vivamus et molestie nisl. Aenean non suscipit velit. Nunc eleifend convallis consectetur. Phasellus ornare dolor eu mi vestibulum, ornare tempus lacus imperdiet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque ut sem ligula. Mauris volutpat vestibulum dui in cursus. Donec aliquam orci pellentesque, interdum neque sit amet, vulputate purus. Quisque volutpat cursus nisl, in volutpat velit lacinia id. Maecenas id felis diam. 
    </p>
    <a href="/">Go back home</a>
    </body>
</html>

一旦完成,编辑原始index.html页面看起来像这样。

<!-- howdy/templates/index.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Howdy!</title>
    </head>
    <body>
        <h1>Howdy! I am Learning Django!</h1>
     <a href="/about/">About Me</a>
    </body>
</html>

点击About me链接将无法正常工作,因为我们的应用没有/about/定义网址。让我们urls.py在我们的howdy应用程序中编辑文件来添加它。

# howdy/urls.py
from django.conf.urls import url
from howdy import views

urlpatterns = [
    url(r'^$', views.HomePageView.as_view()),
    url(r'^about/$', views.AboutPageView.as_view()), # Add this /about/ route
]

一旦我们添加了路由,我们需要添加一个视图来渲染about.html模板,当我们访问/about/url。让我们views.py在howdy应用程序中编辑文件。

# howdy/views.py
from django.shortcuts import render
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    def get(self, request, **kwargs):
        return render(request, 'index.html', context=None)

# Add this view
class AboutPageView(TemplateView):
    template_name = "about.html"

现在运行服务器并访问主页应显示我们的原始模板,并添加关于新页面的新增链接。 点击About me链接应该会引导你到About页面。 About me页面上,点击Go back home链接将重定向到我们原始的索引页面。尝试编辑这两个模板以添加有关您的更多信息。

结论

这只是简单的看看如何让Django的网站开始运行。您可以在官方Django文档中阅读更多有关Django的信息。本教程的完整代码也可以在Github上找到。

https://scotch.io/tutorials/build-your-first-python-and-django-application#toc-some-python-code-samples