本文爲做者原創,轉載請註明出處(http://www.cnblogs.com/mar-q/)by 負贔屓css
django-admin.py startproject placeholder --template=template
urlpatterns=[ url(u'^$',index, name='homepage'), url(u'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$', placeholder, name='placeholder'), ]
DEBUG = os.environ.get('DEBUG','on')=='on' SECRET_KEY = os.environ.get('SECRET_KEY', '&8x8ono))lhdi_6fg!h_9uv3l97w$m$(m6lg&0tttyb2e_lnlv') ALLOWED_HOSTS=['*'] BASE_DIR = os.path.dirname(__file__) settings.configure( DEBUG=DEBUG, SECRET_KEY=SECRET_KEY, ROOT_URLCONF=__name__, ALLOWED_HOSTS=ALLOWED_HOSTS, MIDDLEWARE=[ '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')], # 'APP_DIRS': True, } ], STATICFILES_DIRS=[ os.path.join(BASE_DIR, 'static'), ], STATIC_URL = '/static/' )
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_formate='PNG'): height = self.cleaned_data['height'] width = self.cleaned_data['width'] key = '{}.{}.{}'.format(width, height, image_formate) content = cache.get(key) ##增長服務器緩存 if content is None: image = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(image) text = '{}x{}'.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,255,255)) content = BytesIO() image.save(content, image_formate) content.seek(0) cache.set(key, content, 60*60) return content
這個ImageForm類是一個表單類,用於接收URL傳遞過來的圖片寬高信息,定義了generate方法,用於生成對應尺寸的佔位圖片,同時增長了cache緩存的設置,檢測到對應尺寸的content先從緩存獲取(Django默認使用本地過程、內存緩存)。html
def generate_etag(req, width, height): content = 'Placeholder: {0}x{1}'.format(width, height) return hashlib.sha1(content.encode('utf-8')).hexdigest() @etag(generate_etag) def placeholder(req, width, height): form = ImageForm({'width':width, 'height':height}) if form.is_valid(): image = form.generate() return HttpResponse(image, content_type='image/png') else: return HttpResponseBadRequest('圖片格式錯誤’) def index(req): example = reverse('placeholder', kwargs={'width':50, 'height':50})##經過url標籤和參數獲取地址 context = { 'example': req.build_absolute_uri(example)##把上面造成的地址傳遞給頁面 } return render_to_response('home.html', context)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Place Holder</title> {% load staticfiles %} <link rel="stylesheet" href="{% static 'site.css' %} " type="text/css"> </head> <body> <h1>Django Placeholder Images</h1> <p>該服務應用的功能是提供圖片佔位符</p> <p>請求服務器響應須要提供圖片的width和height參數<b>/image/<width>x<height>/</b></p> <pre> < img src="{{ example }}" ></pre> <h2>Example</h2> <ul> <li><img src="{% url 'placeholder' width=50 height=50 %}"></li> <li><img src="{% url 'placeholder' width=100 height=50 %}"></li> <li><img src="{% url 'placeholder' width=50 height=100 %}"></li> </ul> </body> </html>
body{ text-align: center; } ul{ list-style: none;font-size:50px } li{ display: inline-block; }
application = get_wsgi_application() if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
python templateHello.py runserver 0.0.0.0:8000 ##或者 gunicorn -w 4 -b 0.0.0.0:8000 hello --log-file=-