重新实践《轻量级DJANGO》这本书
从手到尾,手写的DJANGO,不借助命令,效果一样的呢。
- import os
- import sys
- import hashlib
- from django.conf import settings
- DEBUG = os.environ.get('DEBUG', 'on') == 'on'
- SECRET_KEY = os.environ.get('SECRET_KEY', '%jv_4#hoaqwig2gu!eg#^ozptd*a@88u(aasv7z!7xt^5(*i&k')
- ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')
- BASE_DIR = os.path.dirname(__file__)
- settings.configure(
- DEBUG=DEBUG,
- TEMPLATE_DEBUG = True,
- SECRET_KEY=SECRET_KEY,
- ALLOWED_HOSTS=ALLOWED_HOSTS,
- ROOT_URLCONF=__name__,
- MIDDLEWARE_CLASSES=(
- 'django.middleware.common.CommonMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.middleware.clickjacking.XFrameOptionsMiddleware',
- ),
- INSTALLED_APPS=(
- 'django.contrib.staticfiles',
- ),
- TEMPLATES = [
- {
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'DIRS': [
- os.path.join(BASE_DIR,'templates').replace('\\', '/'),
- ],
- 'APP_DIRS': True,
- }
- ],
- STATICFILES_DIRS=(
- os.path.join(BASE_DIR, 'static'),
- ),
- STATIC_URL='/static/',
- )
- from django import forms
- from django.conf.urls import url
- from django.core.urlresolvers import reverse
- from django.core.cache import cache
- from django.core.wsgi import get_wsgi_application
- from django.http import HttpResponse, HttpResponseBadRequest
- from django.shortcuts import render
- from django.views.decorators.http import etag
- from io import BytesIO
- from PIL import Image, ImageDraw
- class ImageForm(forms.Form):
- height = forms.IntegerField(min_value=1, max_value=2000)
- width = forms.IntegerField(min_value=1, max_value=2000)
- def generate(self, image_format='PNG'):
- """Generate an image of the given type and return as raw bytes."""
- height = self.cleaned_data['height']
- width = self.cleaned_data['width']
- key = '{}.{}.{}'.format(width, height, image_format)
- content = cache.get(key)
- if content is None:
- image = Image.new('RGB', (width, height))
- draw = ImageDraw.Draw(image)
- text = '{} X {} demo'.format(width, height)
- textwidth, textheight = draw.textsize(text)
- if textwidth < width and textheight < height:
- texttop = (height - textheight) // 2
- textleft = (width - textwidth) // 2
- draw.text((textleft, texttop), text, fill=(255, 155, 5))
- content = BytesIO()
- image.save(content, image_format)
- content.seek(0)
- cache.set(key, content, 60 * 60)
- return content
- def generate_etag(request, width, height):
- content = 'Placeholder: {0} x {1}'.format(width, height)
- return hashlib.sha1(content.encode('utf-8')).hexdigest()
- @etag(generate_etag)
- def placeholder(request, width, height):
- form = ImageForm({'height': height, 'width': width})
- if form.is_valid():
- image = form.generate()
- return HttpResponse(image, content_type='image/png')
- else:
- return HttpResponseBadRequest("Invalid Image Request")
- def index(request):
- example = reverse('placeholder', kwargs={'width': 500, 'height': 500})
- print example, '#####################'
- context = {
- 'example': request.build_absolute_uri(example)
- }
- print context, '@@@@@@@@@@@@@@@@@@@@@@@'
- return render(request, 'home.html', context)
- urlpatterns = (
- url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$', placeholder, name='placeholder'),
- url(r'^$', index, name='homepage'),
- )
- application = get_wsgi_application()
- if __name__ == "__main__":
- from django.core.management import execute_from_command_line
- execute_from_command_line(sys.argv)
重新实践《轻量级DJANGO》这本书的更多相关文章
- Django项目实践4 - Django网站管理(后台管理员)
http://blog.csdn.net/pipisorry/article/details/45079751 上篇:Django项目实践3 - Django模型 Introduction 对于某一类 ...
- Django项目实践4 - Django站点管理(后台管理员)
http://blog.csdn.net/pipisorry/article/details/45079751 上篇:Django项目实践3 - Django模型 Introduction 对于某一类 ...
- 轻量级django 一
from django.http import HttpResponse from django.conf.urls import url from django.conf import settin ...
- Django应用部署 - 上线指南
http://blog.csdn.net/pipisorry/article/details/46957613 python manage.py runserver已经很接近于服务器的形式,但是并不能 ...
- 《AngularJS深度剖析与最佳实践》简介
由于年末将至,前阵子一直忙于工作的事务,不得已暂停了微信订阅号的更新,我将会在后续的时间里尽快的继续为大家推送更多的博文.毕竟一个人的力量微薄,精力有限,希望大家能理解,仍然能一如既往的关注和支持sh ...
- [原创]django+ldap+memcache实现单点登录+统一认证
前言 由于公司内部的系统越来越多,为了方便用户使用,通过django进行了单点登录和统一认证的尝试,目前实现了django项目的单点登录和非django项目的统一认证,中间波折挺多,涉及的技术包括dj ...
- django view
当请求一个页面时,Django 创建一个包含有关请求数据的 HttpRequest 对象,并将它作为第一个参数传给视图函数,每个视图函数处理完相应逻辑后返回一个 HttpResponse 对象,Htt ...
- Django Web开发【1】Django简介
前言 看完<Django Book>之后, 总想找个实例来实战开发下,无奈国内Django的书籍相当少,只能从英文书籍中吸取养料,偶然之后得到Learning Website Develo ...
- 无状态的web应用(单个py文件的Django占位图片服务器)
本文为作者原创,转载请注明出处(http://www.cnblogs.com/mar-q/)by 负赑屃 阅读本文建议了解Django框架的基本工作流程,了解WSGI应用,如果对以上不是很清楚,建议结 ...
随机推荐
- jenkins 插件
- Python数据分析【炼数成金15周完整课程】
点击了解更多Python课程>>> Python数据分析[炼数成金15周完整课程] 课程简介: Python是一种面向对象.直译式计算机程序设计语言.也是一种功能强大而完善的通用型语 ...
- ubuntu中卸载没有安装完全的软件包
sudo apt-get autoclean sudo apt-get clean sudo apt-get autoremove
- Anaconda安装和环境的搭建
Anaconda安装 在官网上下载最新的Anaconda https://www.anaconda.com/distribution/ 我使用的是2018.12,Python 3.7这个版本的. 安装 ...
- python 类的封装/property类型/和对象的绑定与非绑定方法
目录 类的封装 类的property特性 类与对象的绑定方法与非绑定方法 类的封装 封装: 就是打包,封起来,装起来,把你丢进袋子里,然后用绳子把袋子绑紧,你还能拿到袋子里的那个人吗? 1.隐藏属性和 ...
- 嵌入式入门学习笔记3:[转]编译linux
摘自:https://blog.csdn.net/baidu_24256693/article/details/80115354 编译Linux是什么意思? Linux内核是Linux操作系统的核心, ...
- ProC第一弹
编译pro*c 的makefile例子 原来只需在makefile中追加include $(ORACLE_HOME)/precomp/lib/env_precomp.mk,其他一切按照makefile ...
- stm32之Cortex系统定时器(SysTick)
转载自:http://www.21ic.com/app/mcu/201811/781135.htm SysTick时钟,俗称“嘀嗒定时器”,它能按设定的时间产生一次中断.控制工程代码中随处可见形如 ...
- Linux学习-灾难复原的考虑
硬件损毁,且具有完整备份的数据时 由于是硬件损毁,所以我们不需要考虑系统软件的不稳定问题,所以可以直接将完整的系统复原回去 即可. 由于软件的问题产生的被攻破资安事件 由于系统的损毁是因为被攻击,此时 ...
- hierarchy viewer不能获取userbuild手机版本的UI布局
步骤很详细:http://maider.blog.sohu.com/255485243.html 其中的第7步命令需要更改为: java -jar smali-2.0.3.jar ./out -o c ...