重新实践《轻量级DJANGO》这本书
生活随笔
收集整理的這篇文章主要介紹了
重新实践《轻量级DJANGO》这本书
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
從手到尾,手寫的DJANGO,不借助命令,效果一樣的呢。
import os import sys import hashlib from django.conf import settingsDEBUG = 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, ImageDrawclass 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) // 2textleft = (width - textwidth) // 2draw.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 contentdef 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_lineexecute_from_command_line(sys.argv)?
轉載于:https://www.cnblogs.com/aguncn/p/6399344.html
總結
以上是生活随笔為你收集整理的重新实践《轻量级DJANGO》这本书的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces Round #39
- 下一篇: git常用命令及分支简介