从手到尾,手写的DJANGO,不借助命令,效果一样的呢。

  1. import os
  2. import sys
  3. import hashlib
  4. from django.conf import settings
  5.  
  6. DEBUG = os.environ.get('DEBUG', 'on') == 'on'
  7. SECRET_KEY = os.environ.get('SECRET_KEY', '%jv_4#hoaqwig2gu!eg#^ozptd*a@88u(aasv7z!7xt^5(*i&k')
  8. ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')
  9. BASE_DIR = os.path.dirname(__file__)
  10.  
  11. settings.configure(
  12. DEBUG=DEBUG,
  13. TEMPLATE_DEBUG = True,
  14. SECRET_KEY=SECRET_KEY,
  15. ALLOWED_HOSTS=ALLOWED_HOSTS,
  16. ROOT_URLCONF=__name__,
  17. MIDDLEWARE_CLASSES=(
  18. 'django.middleware.common.CommonMiddleware',
  19. 'django.middleware.csrf.CsrfViewMiddleware',
  20. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  21. ),
  22. INSTALLED_APPS=(
  23. 'django.contrib.staticfiles',
  24. ),
  25. TEMPLATES = [
  26. {
  27. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  28. 'DIRS': [
  29. os.path.join(BASE_DIR,'templates').replace('\\', '/'),
  30. ],
  31. 'APP_DIRS': True,
  32. }
  33. ],
  34. STATICFILES_DIRS=(
  35. os.path.join(BASE_DIR, 'static'),
  36. ),
  37. STATIC_URL='/static/',
  38. )
  39.  
  40. from django import forms
  41. from django.conf.urls import url
  42. from django.core.urlresolvers import reverse
  43. from django.core.cache import cache
  44. from django.core.wsgi import get_wsgi_application
  45. from django.http import HttpResponse, HttpResponseBadRequest
  46. from django.shortcuts import render
  47. from django.views.decorators.http import etag
  48. from io import BytesIO
  49. from PIL import Image, ImageDraw
  50.  
  51. class ImageForm(forms.Form):
  52. height = forms.IntegerField(min_value=1, max_value=2000)
  53. width = forms.IntegerField(min_value=1, max_value=2000)
  54.  
  55. def generate(self, image_format='PNG'):
  56. """Generate an image of the given type and return as raw bytes."""
  57.  
  58. height = self.cleaned_data['height']
  59. width = self.cleaned_data['width']
  60. key = '{}.{}.{}'.format(width, height, image_format)
  61. content = cache.get(key)
  62. if content is None:
  63. image = Image.new('RGB', (width, height))
  64. draw = ImageDraw.Draw(image)
  65. text = '{} X {} demo'.format(width, height)
  66. textwidth, textheight = draw.textsize(text)
  67. if textwidth < width and textheight < height:
  68. texttop = (height - textheight) // 2
  69. textleft = (width - textwidth) // 2
  70. draw.text((textleft, texttop), text, fill=(255, 155, 5))
  71. content = BytesIO()
  72. image.save(content, image_format)
  73. content.seek(0)
  74. cache.set(key, content, 60 * 60)
  75. return content
  76.  
  77. def generate_etag(request, width, height):
  78. content = 'Placeholder: {0} x {1}'.format(width, height)
  79. return hashlib.sha1(content.encode('utf-8')).hexdigest()
  80.  
  81. @etag(generate_etag)
  82. def placeholder(request, width, height):
  83. form = ImageForm({'height': height, 'width': width})
  84. if form.is_valid():
  85. image = form.generate()
  86. return HttpResponse(image, content_type='image/png')
  87. else:
  88. return HttpResponseBadRequest("Invalid Image Request")
  89.  
  90. def index(request):
  91. example = reverse('placeholder', kwargs={'width': 500, 'height': 500})
  92. print example, '#####################'
  93. context = {
  94. 'example': request.build_absolute_uri(example)
  95. }
  96. print context, '@@@@@@@@@@@@@@@@@@@@@@@'
  97. return render(request, 'home.html', context)
  98.  
  99. urlpatterns = (
  100. url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$', placeholder, name='placeholder'),
  101. url(r'^$', index, name='homepage'),
  102. )
  103.  
  104. application = get_wsgi_application()
  105.  
  106. if __name__ == "__main__":
  107. from django.core.management import execute_from_command_line
  108. execute_from_command_line(sys.argv)

重新实践《轻量级DJANGO》这本书的更多相关文章

  1. Django项目实践4 - Django网站管理(后台管理员)

    http://blog.csdn.net/pipisorry/article/details/45079751 上篇:Django项目实践3 - Django模型 Introduction 对于某一类 ...

  2. Django项目实践4 - Django站点管理(后台管理员)

    http://blog.csdn.net/pipisorry/article/details/45079751 上篇:Django项目实践3 - Django模型 Introduction 对于某一类 ...

  3. 轻量级django 一

    from django.http import HttpResponse from django.conf.urls import url from django.conf import settin ...

  4. Django应用部署 - 上线指南

    http://blog.csdn.net/pipisorry/article/details/46957613 python manage.py runserver已经很接近于服务器的形式,但是并不能 ...

  5. 《AngularJS深度剖析与最佳实践》简介

    由于年末将至,前阵子一直忙于工作的事务,不得已暂停了微信订阅号的更新,我将会在后续的时间里尽快的继续为大家推送更多的博文.毕竟一个人的力量微薄,精力有限,希望大家能理解,仍然能一如既往的关注和支持sh ...

  6. [原创]django+ldap+memcache实现单点登录+统一认证

    前言 由于公司内部的系统越来越多,为了方便用户使用,通过django进行了单点登录和统一认证的尝试,目前实现了django项目的单点登录和非django项目的统一认证,中间波折挺多,涉及的技术包括dj ...

  7. django view

    当请求一个页面时,Django 创建一个包含有关请求数据的 HttpRequest 对象,并将它作为第一个参数传给视图函数,每个视图函数处理完相应逻辑后返回一个 HttpResponse 对象,Htt ...

  8. Django Web开发【1】Django简介

    前言 看完<Django Book>之后, 总想找个实例来实战开发下,无奈国内Django的书籍相当少,只能从英文书籍中吸取养料,偶然之后得到Learning Website Develo ...

  9. 无状态的web应用(单个py文件的Django占位图片服务器)

    本文为作者原创,转载请注明出处(http://www.cnblogs.com/mar-q/)by 负赑屃 阅读本文建议了解Django框架的基本工作流程,了解WSGI应用,如果对以上不是很清楚,建议结 ...

随机推荐

  1. jenkins 插件

  2. Python数据分析【炼数成金15周完整课程】

    点击了解更多Python课程>>> Python数据分析[炼数成金15周完整课程] 课程简介: Python是一种面向对象.直译式计算机程序设计语言.也是一种功能强大而完善的通用型语 ...

  3. ubuntu中卸载没有安装完全的软件包

    sudo apt-get autoclean sudo apt-get clean sudo apt-get autoremove

  4. Anaconda安装和环境的搭建

    Anaconda安装 在官网上下载最新的Anaconda https://www.anaconda.com/distribution/ 我使用的是2018.12,Python 3.7这个版本的. 安装 ...

  5. python 类的封装/property类型/和对象的绑定与非绑定方法

    目录 类的封装 类的property特性 类与对象的绑定方法与非绑定方法 类的封装 封装: 就是打包,封起来,装起来,把你丢进袋子里,然后用绳子把袋子绑紧,你还能拿到袋子里的那个人吗? 1.隐藏属性和 ...

  6. 嵌入式入门学习笔记3:[转]编译linux

    摘自:https://blog.csdn.net/baidu_24256693/article/details/80115354 编译Linux是什么意思? Linux内核是Linux操作系统的核心, ...

  7. ProC第一弹

    编译pro*c 的makefile例子 原来只需在makefile中追加include $(ORACLE_HOME)/precomp/lib/env_precomp.mk,其他一切按照makefile ...

  8. stm32之Cortex系统定时器(SysTick)

    转载自:http://www.21ic.com/app/mcu/201811/781135.htm   SysTick时钟,俗称“嘀嗒定时器”,它能按设定的时间产生一次中断.控制工程代码中随处可见形如 ...

  9. Linux学习-灾难复原的考虑

    硬件损毁,且具有完整备份的数据时 由于是硬件损毁,所以我们不需要考虑系统软件的不稳定问题,所以可以直接将完整的系统复原回去 即可. 由于软件的问题产生的被攻破资安事件 由于系统的损毁是因为被攻击,此时 ...

  10. hierarchy viewer不能获取userbuild手机版本的UI布局

    步骤很详细:http://maider.blog.sohu.com/255485243.html 其中的第7步命令需要更改为: java -jar smali-2.0.3.jar ./out -o c ...