重新实践《轻量级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应用,如果对以上不是很清楚,建议结 ...
随机推荐
- Java求字符串中出现次数最多的字符
Java求字符串中出现次数最多的字符 [尊重原创,转载请注明出处]http://blog.csdn.net/guyuealian/article/details/51933611 Java ...
- leetcode-12-stack
409. Longest Palindrome Given a string which consists of lowercase or uppercase letters, find the le ...
- 数字pid笔记(1)
针对stm32中可以如下实现: p->IncrementVal = (p->Kp * (p->err - p->err_next)) + (p->Ki * p->e ...
- 使用Blend的一些问题和技巧
WPF开发,界面处理首选Blend,如果你开发了两年WPF都没接触过blend(当然这种几率不高),或者你刚接触WPF,可以考虑使用Blend,这货也算得上一个神器,上手也不难.以下有两位讲得不错,大 ...
- HDU 5527 Too Rich 贪心
题意: 有\(10\)种面值为\(1, 5, 10, 20, 50, 100, 200, 500, 1000, 2000\)的纸币,现在你要选最多的数量凑成\(p\)块钱. 分析: 同样分析问题的反面 ...
- UVa 10723 LCS变形 Cyborg Genes
题解转自: UVA 10723 Cyborg Genes - Staginner - 博客园 首先这个题目肯定是按最长公共子序列的形式进行dp的,因为只有保证消去的一部分是最长公共子序列才能保证最后生 ...
- SSM网上商城项目 01
开发环境与技术选型 操作系统:win7 IDE:Eclipse neno JDK:1.8 数据库:mysql5.6 Dao层:mybatis.数据库连接池(德鲁伊druid) 缓存:redis3.0. ...
- 提交AppStore被拒原因总结
(1)Information Needed We began the review of your app but aren’t able to continue because we need ad ...
- web安全测试---AppScan扫描工具(转)
安全测试应该是测试中非常重要的一部分,但他常常最容易被忽视掉. 尽管国内经常出现各种安全事件,但没有真正的引起人们的注意.不管是开发还是测试都不太关注产品的安全.当然,这也不能怪我们苦B的“民工兄弟” ...
- LPSTR LPCSTR LPWSTR LPCWSTR区别
LPSTR 一个32位的指向字符串的指针 LPCSTR 一个32位的指向字符串常量的指针 LPWSTR 一个32位的指向unicode字符串的指针 LPCWSTR 个 ...