导读:今天首席CTO笔记来给各位分享关于django路由是如何实现的相关内容,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
ajax请求接口里的数据,然后显示在页面里
1、在模板中使用了jQuery插件封装的ajax,我用到的是get请求,这在django中涉及到模板和静态文件的使用。
2、然后配置路由,因为我们在ajax中请求的路由地址是getdata,所以在django路由中也要设计这个路由url,并且用views的函数处理路由。
3、然后用视图函数处理对应路由url的请求,然后导入方法JsonResponse,然后我自定义一个字符串,并且用键值对字典的形式返回。注意,最好用JsonResponse方法返回数据,不然可能得不到json格式的数据。
4、get请求中的data参数就是存储后台返回的数据的,但是这个数据是json格式的,所以我们可以通过data.键名(刚才定义的u),这样就可以取出数据了。
5、运行django服务器之后,点击按钮,那么就会开始请求数据,然后弹出数据。可以看到数据跟后台定义的数据一模一样。
Django源码阅读 (一) 项目的生成与启动
诚实的说,直到目前为止,我并不欣赏django。在我的认知它并不是多么精巧的设计。只是由功能堆积起来的"成熟方案"。但每一样东西的崛起都是时代的选择。无论你多么不喜欢,但它被需要。希望有一天,python能有更多更丰富的成熟方案,且不再被诟病性能和可维护性。(屁话结束)
取其精华去其糟粕,django的优点是方便,我们这次源码阅读的目的是探究其方便的本质。计划上本次源码阅读不会精细到每一处,而是大体以功能为单位进行解读。
django-admin startproject HelloWorld 即可生成django项目,命令行是exe格式的。
manage.py 把参数交给命令行解析。
execute_from_command_line() 通过命令行参数,创建一个管理类。然后运行他的 execute() 。
如果设置了reload,将会在启动前先 check_errors 。
check_errors() 是个闭包,所以上文结尾是 (django.setup)() 。
直接看最后一句 settings.INSTALLED_APPS 。从settings中抓取app
注意,这个settings还不是我们项目中的settings.py。而是一个对象,位于 django\conf\__init__.py
这是个Settings类的懒加载封装类,直到 __getattr__ 取值时才开始初始化。然后从Settings类的实例中取值。且会讲该值赋值到自己的 __dict__ 上(下次会直接在自己身上找到,因为 __getattr__ 优先级较低)
为了方便debug,我们直接写个run.py。不用命令行的方式。
项目下建个run.py,模拟runserver命令
debug抓一下setting_module
回到 setup() 中的最后一句 apps.populate(settings.INSTALLED_APPS)
开始看 apps.populate()
首先看这段
这些App最后都会封装成为AppConfig。且会装载到 self.app_configs 字典中
随后,分别调用每个appConfig的 import_models() 和 ready() 方法。
App的装载部分大体如此
为了方便debug我们改写下最后一句
res的类型是 Command django.contrib.staticfiles.management.commands.runserver.Command object at 0x00000101ED5163A0
重点是第二句,让我们跳到 run_from_argv() 方法,这里对参数进行了若干处理。
用pycharm点这里的handle会进入基类的方法,无法得到正确的走向。实际上子类Commond重写了这个方法。
这里分为两种情况,如果是reload重载时,会直接执行 inner_run() ,而项目启动需要先执行其他逻辑。
django 项目启动时,实际上会启动两次,如果我们在项目入口(manage.py)中设置个print,会发现它会打印两次。
第一次启动时, DJANGO_AUTORELOAD_ENV 为None,无法进入启动逻辑。会进入 restart_with_reloader() 。
在这里会将 DJANGO_AUTORELOAD_ENV 置为True,随后重启。
第二次时,可以进入启动逻辑了。
这里创建了一个django主线程,将 inner_run() 传入。
随后本线程通过 reloader.run(django_main_thread) ,创建一个轮询守护进程。
我们接下来看django的主线程 inner_run() 。
当我们看到wsgi时,django负责的启动逻辑,就此结束了。接下来的工作交由wsgi服务器了
这相当于我们之前在fastapi中说到的,将fastapi的app交由asgi服务器。(asgi也是django提出来的,两者本质同源)
那么这个wsgi是从哪来的?让我们来稍微回溯下
这个settings是一个对象,在之前的操作中已经从 settings.py 配置文件中获得了自身的属性。所以我们只需要去 settings.py 配置文件中寻找。
我们来寻找这个 get_wsgi_application() 。
它会再次调用 setup() ,重要的是,返回一个 WSGIHandler 类的实例。
这就是wsgiapp本身。
load_middleware() 为构建中间件堆栈,这也是wsgiapp获取setting信息的唯一途径。导入settings.py,生成中间件堆栈。
如果看过我之前那篇fastapi源码的,应该对中间件堆栈不陌生。
app入口→中间件堆栈→路由→路由节点→endpoint
所以,wsgiapp就此构建完毕,服务器传入请求至app入口,即可经过中间件到达路由进行分发。
如何创建一个Django网站
本文演示如何创建一个简单的 django 网站,使用的 django 版本为1.7。
1. 创建项目
运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :
$ django-admin.py startproject mysite
创建后的项目目录如下:
mysite
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
1 directory, 5 files
说明:
__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。
manage.py :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python manage.py help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。
settings.py :该 Django 项目的设置或配置。
urls.py:Django项目的URL路由设置。目前,它是空的。
wsgi.py:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI
接下来,你可以修改 settings.py 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONE
SITE_ID = 1
LANGUAGE_CODE = 'zh_CN'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True
上面开启了 [Time zone]() 特性,需要安装 pytz:
$ sudo pip install pytz
2. 运行项目
在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
然后启动服务:
$ python manage.py runserver
你会看到下面的输出:
Performing system checks...
System check identified no issues (0 silenced).
January 28, 2015 - 02:08:33
Django version 1.7.1, using settings 'mysite.settings'
Starting development server at
Quit the server with CONTROL-C.
这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问。 既然服务器已经运行起来了,现在用网页浏览器访问 。你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。
你也可以指定启动端口:
$ python manage.py runserver 8080
以及指定 ip:
$ python manage.py runserver 0.0.0.0:8000
3. 创建 app
前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块。
在项目目录下创建一个 app:
$ python manage.py startapp polls
如果操作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:
polls
├── __init__.py
├── admin.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
1 directory, 6 files
4. 创建模型
每一个 Django Model 都继承自 django.db.models.Model
在 Model 当中每一个属性 attribute 都代表一个 database field
通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句
打开 polls 文件夹下的 models.py 文件。创建两个模型:
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date = timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
然后在 mysite/settings.py 中修改 INSTALLED_APPS 添加 polls:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:
$ python manage.py makemigrations polls
你会看到下面的输出日志:
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
你可以从 polls/migrations/0001_initial.py 查看迁移语句。
运行下面语句,你可以查看迁移的 sql 语句:
$ python manage.py sqlmigrate polls 0001
输出结果:
BEGIN;
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));
INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";
DROP TABLE "polls_choice";
ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";
CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");
COMMIT;
你可以运行下面命令,来检查数据库是否有问题:
$ python manage.py check
再次运行下面的命令,来创建新添加的模型:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
Applying polls.0001_initial... OK
总结一下,当修改一个模型时,需要做以下几个步骤:
修改 models.py 文件
运行 python manage.py makemigrations 创建迁移语句
运行 python manage.py migrate,将模型的改变迁移到数据库中
你可以阅读 django-admin.py documentation,查看更多 manage.py 的用法。
创建了模型之后,我们可以通过 Django 提供的 API 来做测试。运行下面命令可以进入到 python shell 的交互模式:
$ python manage.py shell
下面是一些测试:
from polls.models import Question, Choice # Import the model classes we just wrote.
# No questions are in the system yet.
Question.objects.all()
[]
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
q.save()
# Now it has an ID. Note that this might say "1L" instead of "1", depending
# on which database you're using. That's no biggie; it just means your
# database backend prefers to return integers as Python long integer
# objects.
q.id
1
# Access model field values via Python attributes.
q.question_text
"What's new?"
q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=UTC)
# Change values by changing the attributes, then calling save().
q.question_text = "What's up?"
q.save()
# objects.all() displays all the questions in the database.
Question.objects.all()
[Question: Question object]
打印所有的 Question 时,输出的结果是 [Question: Question object],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:
from django.db import models
class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
接下来继续测试:
from polls.models import Question, Choice
# Make sure our __str__() addition worked.
Question.objects.all()
[Question: What's up?]
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
Question.objects.filter(id=1)
[Question: What's up?]
Question.objects.filter(question_text__startswith='What')
[Question: What's up?]
# Get the question that was published this year.
from django.utils import timezone
current_year = timezone.now().year
Question.objects.get(pub_date__year=current_year)
Question: What's up?
# Request an ID that doesn't exist, this will raise an exception.
Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
Question.objects.get(pk=1)
Question: What's up?
# Make sure our custom method worked.
q = Question.objects.get(pk=1)
# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
q = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
q.choice_set.all()
[]
# Create three choices.
q.choice_set.create(choice_text='Not much', votes=0)
Choice: Not much
q.choice_set.create(choice_text='The sky', votes=0)
Choice: The sky
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
c.question
Question: What's up?
# And vice versa: Question objects get access to Choice objects.
q.choice_set.all()
[Choice: Not much, Choice: The sky, Choice: Just hacking again]
q.choice_set.count()
3
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
Choice.objects.filter(question__pub_date__year=current_year)
[Choice: Not much, Choice: The sky, Choice: Just hacking again]
# Let's delete one of the choices. Use delete() for that.
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete()
上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。
5. 管理 admin
Django有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容.
新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settings.py:
INSTALLED_APPS = (
'django.contrib.admin', #默认添加后台管理功能
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite',
)
同时也已经添加了进入后台管理的 url, 可以在 mysite/urls.py 中查看:
url(r'^admin/', include(admin.site.urls)), #可以使用设置好的url进入网站后台
接下来我们需要创建一个管理用户来登录 admin 后台管理界面:
$ python manage.py createsuperuser
Username (leave blank to use 'june'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
总结
最后,来看项目目录结构:
mysite
├── db.sqlite3
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
├── polls
│ ├── __init__.py
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ ├── models.py
│ ├── templates
│ │ └── polls
│ │ ├── detail.html
│ │ ├── index.html
│ │ └── results.html
│ ├── tests.py
│ ├── urls.py
│ ├── views.py
└── templates
└── admin
└── base_site.htm
通过上面的介绍,对 django 的安装、运行以及如何创建视 图和模型有了一个清晰的认识,接下来就可以深入的学习 django 的自动化测试、持久化、中间件、国 际 化等知识。
【Django】路由配置:反向解析、重定向
简单的路由配置
【注意事项】:
(1):若要从URL 中捕获一个值,只需要在它周围放置一对圆括号。
(2):不需要添加一个前导的反斜杠,因为每个URL 都有。例如,应该是^articles 而不是 ^/articles。
(3):每个正则表达式前面的'r' 是可选的但是建议加上。它告诉Python 这个字符串是“原始的” —— 字符串中任何字符都不应该转义
(4):urlpatterns中的元素按照书写顺序从上往下逐一匹配正则表达式,一旦匹配成功则不再继续
在使用Django 项目时,一个常见的需求是获得URL 的最终形式,以用于嵌入到生成的内容中(视图中和显示给用户的URL等)或者用于处理服务器端的导航(重定向等)。
在需要URL 的地方,对于不同层级,Django 提供不同的工具用于URL 反查:
反向解析的过程:用户通过 /login/ 这个接口 到达urls.py,然后通过 path("login/",views.login,name="log") 到达 views.py(用于视图函数)
在实现逻辑功能时,可能会需要实现重定向的功能。
(1)、通过redirect函数或HttpResponseRedirect函数硬编码的形式
(2)、通过URLconf路由命名空间的形式。
(3)、如果在逻辑函数中不做任何处理,可以直接在url中配置。
Django路由系统(一)
urlpatterns = [
url(正则表达式, views视图函数,参数,别名),
]
注意:
Django 2.0版本中的路由系统已经替换成下面的写法( 官方文档 ):url替换成path
参数说明:
正则表达式:一个正则表达式字符串,网站访问路径
views视图函数:一个可调用对象,通常为一个视图函数或一个指定视图函数路径的字符串
参数:可选的要传递给视图函数的默认参数(字典形式)
别名:一个可选的name参数
注意事项
urlpatterns中的元素按照书写顺序从上往下逐一匹配正则表达式,一旦匹配成功则不再继续。
若要从URL中捕获一个值,只需要在它周围放置一对圆括号(分组匹配)。
不需要添加一个前导的反斜杠,因为每个URL 都有。例如,应该是^articles 而不是 ^/articles。
每个正则表达式前面的'r' 是可选的但是建议加上。
是否开启URL访问地址后面不为/跳转至带有/的路径的配置项
APPEND_SLASH=True
Django settings.py配置文件中默认没有 APPEND_SLASH 这个参数,但 Django 默认这个参数为 APPEND_SLASH = True。 其作用就是自动在网址结尾加'/'。
如果在 settings.py 中设置了 APPEND_SLASH=False,此时我们再请求 时就会提示找不到页面。
上面的示例使用简单的正则表达式分组匹配(通过圆括号)来捕获URL中的值并以位置参数形式传递给视图。
在更高级的用法中,可以使用分组命名匹配的正则表达式组来捕获URL中的值并以关键字参数形式传递给视图。
在Python的正则表达式中,分组命名正则表达式组的语法是(?Pnamepattern),其中name是组的名称,pattern是要匹配的模式。
比如:注意P是大写
def test(request,year,month):函数引入year和month
以上方式捕获的参数永远都是字符串
每个在URLconf中捕获的参数都作为一个普通的Python字符串传递给视图,无论正则表达式使用的是什么匹配方式。
结语:以上就是首席CTO笔记为大家介绍的关于django路由是如何实现的全部内容了,希望对大家有所帮助,如果你还想了解更多这方面的信息,记得收藏关注本站。
以上内容为新媒号(sinv.com.cn)为大家提供!新媒号,坚持更新大家所需的互联网后端知识。希望您喜欢!
版权申明:新媒号所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 k2#88.com(替换@) 举报,一经查实,本站将立刻删除。