Django内置的server基本包括两部分:django.core.servers和django.core.handlers

Django源码分析之server 乍见 Django内置的server基本包括两部分:django.core.servers和django.core.handlers相识 servers.basehttp是Django自身提供的一个用于开发测试的server模块,其中提供的WSGIServer、ServerHandler、WSGIRequestHandler其实都是属于WSGI server,django只不过是对python内置的 阅读详情


Django内置的server基本包括两部分:django.core.servers和django.core.handlers


相识
servers.basehttp是Django自身提供的一个用于开发测试的server模块,其中提供的WSGIServer、ServerHandler、WSGIRequestHandler其实都是属于WSGI server,django只不过是对python内置的WSGI模块simple_server做的一层包装。

handlers package包括base.py和wsgi.py两个模块。
base.py中只定义了一个BaseHandler类,它复杂一些基础的功能,比如加载中间件,处理异常,获取响应数据等

wsgi.py才是主角,其中最重要的就是WSGIHandler类,它继承了base.py中的BaseHandler,只添加了一个__call__方法,那为什么添加这个方法呢?

django.core.wsgi

import django
from django.core.handlers.wsgi import WSGIHandler


def get_wsgi_application():
    """
    The public interface to Django's WSGI support. Should return a WSGI
    callable.

    Allows us to avoid making django.core.handlers.WSGIHandler public API, in
    case the internal WSGI implementation changes or moves in the future.
    """
    django.setup()
    return WSGIHandler()
可见我们启动server时传入的application其实是WSGIHandler的一个实例,而根据WSGI规范,这个application必须要是callable,python中的callable包括函数、方法以及任何定义了__call__方法的对象

回到handlers.wsgi

class WSGIHandler(base.BaseHandler):
    initLock = Lock()
    request_class = WSGIRequest

    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialized.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%s %s' % (response.status_code, response.reason_phrase)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
        start_response(force_str(status), response_headers)
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response
由于__call__是一个请求的入口,它需要调用BaseHandler中定义的方法去执行加载中间件等一系列操作和异常处理,除此之外,WSGIHandler还会处理cookie、触发signal等。

至于如何返回响应,具体可看handlers.base模块,大概就是找出请求的path,通过匹配路由,找到并执行用户定义的view方法,执行中间件处理方法,最后返回响应。当然,还有一系列的异常处理。

Tornado异步框架深度解析:从事件循环到高并发实战 异步编程是现代高性能Web服务的核心技术,其核心思想是通过非阻塞I/O和事件驱动模型,让单线程在等待I/O操作时能够处理其他任务,从而极大提升服务器的并发处理能力。这种模型特别适合I/O密集型应用,如实时通信、API网关和高并发请求场景。Tornado作为Python生态中一个成熟且纯粹的异步网络框架,其核心价值在于原生、高效地解决了C10K乃至C100K问题。它通过事件循环(Event Loop)和IOLoop实现高效调度,并提供了基于协程的异步编程范式,让开发者能够以接近同步代码的清晰度编写高性能异步应 阅读详情

相关推荐

Django讲课笔记04:Django项目的调试

文章目录零、本讲学习目标一、课程导入二、新课讲授(一)PyCharm运行命令创建的Django项目1、打开第03讲里的MyDjango项目2、配置Django Server3、图形界面运行项目4、终端命令运行项目(二)PyCharm调试Django项目1、修改index/views.py2、设置断点3、开始调试4、各按钮功能三、课堂小结四、课后作业五、拓展内容 零、本讲学习目标 会在PyCharm社区版中运行Django项目 会Django项目的调试 会Django项目的相关简单配置 一、课程导入 创

howard2005的专栏 5419

Django

ubuntu下安装: http://linux265.com/news/3453.html

weixin_43591355的博客 486

麒麟系统下的多媒体革命:VLC在kylinV10上的性能优化与调试技巧

本文详细介绍了在麒麟kylinV10系统上优化VLC多媒体播放性能的实战技巧,特别针对飞腾FT-2000/4硬件平台。从源码编译调优到硬件加速配置,提供全面的性能提升方案,帮助开发者在国产操作系统上构建高效媒体播放环境。

weixin_29168675的博客 457

Django的runserver

set_app执行的是fromwsgiref.simple_serverimportWSGIServer下的方法。serve_forever执行的是fromsocketserverimportBaseServer。,并且根据需要扩展了相关功能,例如支持IPv6和定制错误处理等。Django在这部分代码中通过自定义的。类与WSGI服务器进行关联。具体来说,Django使用。作为服务器基础类,它继承了。

Azx的博客 895

【TestNG自动化测试框架详解】

TestNG是一款设计测试用例执行流程的测试框架。

weixin_43936332的博客 1539

从零构建高精度电子秤:HX711与STM32的时序通信陷阱与实战避坑指南

本文详细解析了使用STM32F103C8T6与HX711模块构建高精度电子秤的通信时序陷阱与实战解决方案。重点探讨了微秒级延迟实现、数据读取算法、校准方法和滤波优化,帮助开发者避开常见通信问题,提升电子秤的测量精度和稳定性。

data3的博客 782

Django自学连载一(认识Django)

认识Django 1. Django简介 Django是什么? Django 是用Python开发的一个免费开源的Web框架,可以用于快速搭建高性能,优雅的网站!采用了MVC->MVT的框架模式。 Django前景 在Python中,与web开发相关的包有13045个,其中django就占了9091个,约70%。同时,Python中活跃的web框架多达54,其中最活跃的包括Django,flask等。Django便是其中的佼佼者,截至目前,已经有超过5200个中大型网站使用Django开发。比较知名的

coffeetogether的博客 550

普元EOS8.3精简版安装指南:从零开始搭建低代码开发环境

本文详细介绍了普元EOS8.3精简版的完整安装流程。从JDK1.8环境准备、MySQL数据库配置与初始化,到核心配置文件修改、服务启动与登录验证,提供了从零开始搭建低代码开发环境的清晰步骤和常见问题排坑指南,帮助开发者快速部署并体验平台核心功能。

ik678901的博客 1102

使用Django-sslserver搭建https服务器和访问

2 使用django-sslserver:在setting.py文件中找到INSTALLED_APPS,在里面添加一行。变量,里面加的是自己服务器开放给外部看的ip,一定得是自己服务器的ip,可以直接放个。(bash)查到地址,端口号就是你自己设置开发端口了,一般本地是。可以不指定,就是使用sslserver默认的证书和密钥。主要就是这种文件做服务,可以看情况建几个。–cert 指定使用的证书。(2)非正常访问,直接设置。忽略CA认证,还是可以用。–key 指定使用的密钥。(1)正常使用证书访问,...

qq_44063711的博客 4341

PPPoE上网配置不求人:华为路由器命令行操作指南(2023最新版)

本文提供2023年最新的华为路由器PPPoE上网配置命令行操作指南。通过详细的步骤讲解,从连接设备、创建拨号接口、绑定PPPoE客户端到配置内网与NAT,手把手教你完成配置,并附有验证排错方法,助你轻松实现稳定上网。

s4t5u6v的博客 679

【异常】安装hermes-agent时提示GnuTLS recv error (-110): The TLS connection was non-properly terminated.

Git克隆仓库时出现TLS连接异常报错的解决方案摘要: 当执行git clone命令时遇到"GnuTLS recv error (-110)"报错,通常由网络不稳定、缓冲区不足或证书验证问题导致。主要解决方案包括:1)增大Git HTTP缓冲区(git config --global http.postBuffer 524288000);2)使用GitHub镜像站加速克隆;3)临时禁用SSL验证进行测试;4)检查并调整代理配置;5)改用SSH协议克隆。建议优先尝试增大缓冲区和镜像站方案,

奶爸的编程之路,也就一周冷个三天 1350

Django之HttpServer服务器分析详解

大家知道,软件的正向工程,是从软件的需求获取开始,大概经历需求分析,概要分析,领域分析,设计分析,详细设计,代码实现,部署,实施这几个步骤,最终交付给用户使用。而在某些时候,比如某个软件产品是用PHP开发的,因为某些原因,我们想移植到JAVA平台去。或者某公司看到某个软件的市场前景很好,想COPY它的主要功能,然后经过加工润色后推出一个具有相同功能,更好用户体...

weixin_33974433的博客 500

华为OD机试真题 新系统 - WIFI设备网络规划 (Java/Py/C/C++/Js/Go)

本文整理华为 OD 机试新系统机考真题库,涵盖高频考点精析与完整题目内容,提供 C 语言、Java、C++、Python、Go、JavaScript 多语言源码实现,搭配详细解题思路讲解,并支持在线 OJ 刷题练习,助力高效备考华为 OD 机试新系统。

算法大师! 2016

反转链表面试:一次讲透迭代与递归两条实现路径

反转链表(LeetCode 206)是链表面试里出现频率最高的题目之一,简单题的标签下藏着对指针操作和递归思维的完整考察。很多候选人卡在同一个地方:思路"想到了",代码写出来却不是漏掉空指针,就是形成死循环。 这道题的全部难度,其实集中在一个矛盾上:**链表里的箭头只能朝一个方向,而反转要求你逐个把箭头掉头,但掉头时又不能把还没处理的节点弄丢**。理解了这一点,迭代和递归两种写法都只是这个矛盾的

gitblog_00351的博客 358

黑猫带你学UFS协议第17篇:UFS安全模式详解(Secure Mode)

本文详细介绍了UFS协议中的安全模式,包括Erase, Discard, Purge和Wipe Device操作。Erase用于永久删除数据并确保无法恢复;Discard不保证数据清除;Purge类似于Sanitize,清除内部未映射的物理块数据;Wipe Device则是格式化设备。这些操作涉及逻辑单元、擦除单位、相关寄存器配置等,确保数据安全。" 126036669,12409270,MySQL 8.0 开窗函数详解,"['数据库理论', 'SQL']

黑猫奥利奥的博客 2559

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

并行分布式框架:Celery、rq、funboost

Celery是一个异步任务的调度工具,也可以叫做 "分布式任务队列(Distributed Task Queue)"。

freeking101的博客 5万+

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

django框架全解

MVC就是把Web应用分为模型(M),控制器©和视图(V)三层,他们之间以一种插件式的、松耦合的方式连接在一起,模型负责业务对象与数据库的映射(ORM),视图负责与用户的交互(页面),控制器接受用户的输入调用模型和视图完成用户的请求。Django的MTV模式本质上和MVC是一样的,也是为了各组件间保持松耦合关系,只是定义上有些许不同,Django的MTV分别是值:除了以上三层之外,还需要一个URL分发器,它的作用是将一个个URL的页面请求分发给不同的View处理,View再调用相应的Model和Templa

General_zy的博客 8701

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

【Django】初识Django&快速上手

Django是一个高级的、开源的Python Web框架,旨在快速、高效地开发高质量的Web应用程序。

m0_72895175的博客 1583

怎样为Django的server配置跨域资源共享(CORS)

为了在 Django 服务器中配置跨域资源共享(CORS),你可以使用库。这个库可以帮你轻松地设置 CORS 规则,从而允许你的 Django 服务器处理来自不同源的请求。

BigBookX's Blog 1104

Django 连接(sqlserver)数据库方法

django 的SQL server适配器,例如django-pyodbc-azure 或 mssql-django

wyk123_046的博客 1124

Django SSL Server 使用教程

Django SSL Server 使用教程 1. 项目的目录结构及介绍 Django SSL Server 是一个为 Django 框架提供的 SSL 启用开发服务器。以下是项目的目录结构及其介绍: django-sslserver/ ├── django_sslserver/ │ ├── __init__.py │ ├── management/ │ │ ├── __init_...

gitblog_00329的博客 616

2022/08/24-学习笔记(十)-pip更改源 django server设置

安装第三方库,更改pip源

m0_52892440的博客 391

django服务器端口如何修改,django 修改server端口号的方法

django 修改server端口号的方法,django,修改,server,端口,号的,方法,djandjango 修改server端口号的方法易采站长站,站长之家为您整理了django 修改server端口号的方法的相关内容。django可以在运行服务器时指定端口号python manage.py runserver 8080我们启动django开发服务器,输入命令 manage.py run...

weixin_39629631的博客 2658

Django底层实现

django框架–底层架构 目录 零、参考 一、对于web服务的理解 二、对于wsgi协议的理解 三、自定义一个简单的基于wsgi协议的web框架 四、django中的server实现 五、django中的application实现 六、django的底层调用链 七、总结 零、参考 https://www.jianshu.com/p/679dee0a4193 https://www.letiantian.me/2015-09-10-understand-python-wsgi/ 一、对于web服务的理解 w

weixin_40374368的博客 832
上一篇: Django源码分析之执行入口
下一篇: uwsgi+nginx
qq_15551663
博客等级 码龄12年 4粉丝 95原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值