Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Using Chart.js with Django
Chart.js is the new kid on on the block for JavaScript charts. Learn how to use them here to chart out the number of user registrations for the last 30 days. The View This view builds an array of people that registered on the site daily for the last 30 days. from django.views.generic import TemplateView from django.contrib.auth.models import User import arrow class AnalyticsIndexView(TemplateView): template_name = 'analytics/admin/index.html' def get_context_data(self, **kwargs): context = super(AnalyticsIndexView, self).get_context_data(**kwargs) context['30_day_registrations'] = self.thirty_day_registrations() return context def thirty_day_registrations(self): final_data = [] date = arrow.now() for day in xrange(1, 30): date = date.replace(days=-1) count = User.objects.filter( date_joined__gte=date.floor('day').datetime, date_joined__lte=date.ceil('day').datetime).count() final_data.append(count) return final_data The method thirty_day_registrations loops through from 1 to 30, and gets the count of registrations for that day. Then it returns that array back to the get_context_data method and assigns it to 30_day_registrations which is what we will use in our template. The Template The template is very basic in that it has just enough data to generate a line chart. {% extends "base.html" %} {% block extrahead %} <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $( document ).ready(function() { var data = { labels: ['1', '5', '10', '15', '20', '25', '30'], datasets: [ { label: "Site … -
Tips for Upgrading Django
From time to time we inherit code bases running outdated versions of Django and part of our work is to get them running a stable and secure version. In the past year we've done upgrades from versions as old as 1.0 and we've learned a few lessons along the way. Tests are a Must You cannot begin a major upgrade without planning how you are going to test that the site works after the upgrade. Running your automated test suite should note warnings for new or pending deprecations. If you don’t have an automated test suite then now would be a good time to start one. You don't need 100% coverage, but the more you have, the more confident you will feel about the upgrade. Integration tests with Django's TestClient can help cover a lot of ground with just a few tests. You'll want to use these sparingly because they tend to be slow and fragile. However, you can use them to test your app much like a human might do, submitting forms (both valid and invalid), and navigating to various pages. As you get closer to your final target version or you find more edge cases, you can add focused unittests to … -
Release 1.2b2
-
Release 1.2b1
-
将 Django 作为 bootstrap 的后台框架
如果你想在Django中使用Bootstrap作为前台框架, 但又不知道如何将他们整合到一起的话, 那么本篇我们就介绍一下使用django自带的staticfiles app将Bootstrip整合到Django中: 首先我们需要在GetBootstrip.com下载Bootstrip. 然后我们解压缩zip文件, 将加压缩的文件放入项目中. 接着在settings.py的STATICFILES_DIRS中添加bootstrip目录. 最后我们使用以下base.html为基础: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Bootstrap | {% block title %}Untitled{% endblock %}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="{{STATIC_URL}}css/bootstrap.css" rel="stylesheet"> <style> body { padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */ } </style> <link href="{{STATIC_URL}}css/bootstrap-responsive.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script src="{{STATIC_URL}}js/jquery-1.8.1.min.js" type="text/javascript"></script> {% block extrahead %} {% endblock %} <script type="text/javascript"> $(function(){ {% block jquery %} {% endblock %} }); </script> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="/">Bootstrap</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="active"><a href="/">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div id="messages"> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}}"> <a class="close" data-dismiss="alert">×</a> {{message}} </div> {% endfor %} {% endif %} </div> <div class="container"> {% block content %} {% endblock %} </div> <!-- /container --> </body> </html> 有了以上base.html之后, 我们就可以按照自己的需求修改并获得最佳效果了. -
使用 pyrrd 收集系统信息
上星期, 我们想测试几个WSGI应用的评分, 由于不同的concurrency模式, 使我们很难一一设置并评测. 其中的系统信息也是一项重要的指标, 例如CPU消耗, 内存消耗等信息的收集和图像化. RRDtool是一个广泛使用的测试工具. 我们可以通过pyrrd和subprocess模块对每个WSGI应用进行测试: from pyrrd.rrd import DataSource, RRA, RRD dss = [ DataSource(dsName='cpu', dsType='GAUGE', heartbeat=4), DataSource(dsName='mem', dsType='GAUGE', heartbeat=4) ] rras = [RRA(cf='AVERAGE', xff=0.5, steps=1, rows=100)] rrd = RRD('/tmp/heartbeat.rrd', ds=dss, rra=rras, step=1) rrd.create() 以上代码将会使用CPU和内存实用信息创建/tem/heartbeat.rrd文件. 两者都定义为GAUGE类型. 然后我们定义了round-robin archive(RRA)来储存最多100个数据点. 在代码最后, 我们使用之前的设置, 以每秒的速度保存到RRD文件中. pyrrd模块使用的属于与rrdtool相同, 因此我们可以使用现成的rrdtool知识. 使用subprocess: pattern = re.compile('\s+') command = '/bin/ps --no-headers -o pcpu,pmem -p %s' % ' '.join(pids) while True: ps = subprocess.check_output(command, shell=True) pcpu = 0.0 pmem = 0.0 for line in ps.split('\n'): if line.strip(): cpu, mem = map(float, pattern.split(line.strip())) pcpu += cpu pmem += mem rrd.bufferValue(time.time(), pcpu, pmem) rrd.update() time.sleep(1) 使用ps命令过滤显示每个pid的%CPU和%MEM使用信息, 然后输出经过处理保存到rrd文件. 请注意, 这不是一个典型的rrdtool使用案例. 通常的使用情形是: # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, with_statement, unicode_literals) import re import signal import sys import time import subprocess from random import random, randint from pyrrd.rrd import DataSource, RRA, RRD def usage(): print('%s rrdfile pid, ...' % __file__) print('sample the %cpu and %mem for specified pids, aggregated') def sigint_handler(signal, frame): print("Sampling finishes: %.2f." % time.time()) sys.exit(0) def main(): rrd_file = sys.argv[1] pids = sys.argv[2:] dss = [ DataSource(dsName='cpu', dsType='GAUGE', heartbeat=4), DataSource(dsName='mem', dsType='GAUGE', heartbeat=4) ] rras = [RRA(cf='AVERAGE', xff=0.5, steps=1, rows=100)] rrd = RRD(rrd_file, ds=dss, rra=rras, step=1) rrd.create() signal.signal(signal.SIGINT, sigint_handler) pattern = re.compile('\s+') command = '/bin/ps … -
Release 1.2b1
-
在Python模块顶层运行的代码引起的一个Bug
几个星期前, 我的同事跑过来, 说发现一个奇怪的Bug: 在使用Python的subprocess运行子进程时, 当子进程运行失败时居然没有抛出错误! 然后我们在Interactive Python prompt中测试了一下: >>> import subprocess >>> subprocess.check_call("false") 0 而在其他机器运行相同的代码时, 却正确的抛出了错误: >>> subprocess.check_call("false") Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 542, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'false' returned non-zero exit status 1 看来是subprecess误以为子进程成功的退出了导致的原因. 深入分析 第一眼看上去, 这一问题应该是Python自身或操作系统引起的. 这到底是怎么发生的? 于是我的同事查看了subprocess的wait()方法: def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" while self.returncode is None: try: pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0) except OSError as e: if e.errno != errno.ECHILD: raise # This happens if SIGCLD is set to be ignored or waiting # for child processes has otherwise been disabled for our # process. This child is dead, we can't get the status. pid = self.pid sts = 0 # Check the pid and loop as waitpid has been known to return # 0 even without WNOHANG in odd situations. issue14396. if pid == self.pid: self._handle_exitstatus(sts) return self.returncode 可见, 如果os.waitpid的ECHILD检测失败, 那么错误就不会被抛出. 通常, 当一个进程结束后, 系统会继续记录其信息, 直到母进程调用wait()方法. 在此期间, 这一进程就叫"zombie". 如果子进程不存在, 那么我们就无法得知其是否成功还是失败了. 以上代码还能解决另外一个问题: Python默认认为子进程成功退出. 大多数情况下, 这一假设是没问题的. 但当一个进程明确表明忽略子进程的SIGCHLD时, waitpid()将永远是成功的. 回到原来的代码中 我们是不是在我们的程序中明确设置忽略SIGCHLD? 不太可能, 因为我们使用了大量的子进程, 但只有极少数情况下才出现同样的问题. 再使用git grep后, 我们发现只有在一段独立代码中, 我们忽略了SIGCHLD. 但这一代吗根本就不是程序的一部分, 只是引用了一下. 一星期后 一星期后, 这一错误又再一次发生. 并且通过简单的调试, 在debugger中重现了该错误. 经过一些测试, 我们确定了正是由于程序忽略了SIGCHLD才引起的这一bug. 但这是怎么发生的呢? 我们查看了那段独立代码, 其中有一段: signal.signal(signal.SIGCHLD, signal.SIG_IGN) 我们是不是无意间import了这段代码到程序中? 结果显示我们的猜测是正确的. 当import了这段代码后, 由于以上语句是在这一module的顶层, 而不是在一个function中, 导致了它的运行, 忽略了SIGCHLD, 从而导致了子进程错误没有被抛出! 总结 这一bug的发生, … -
Python Deque 模块简单介绍和示例
Deque模块是Python标准库collections中的一项. 它提供了两端都可以操作的序列, 这意味着, 你可以在序列前后都执行添加或删除. 创建Deque序列: from collections import deque d = deque() Deque提供了类似list的操作方法: d = deque() d.append('1') d.append('2') d.append('3') len(d) d[0] d[-1] 输出结果: 3 '1' '3' 两端都使用pop: d = deque('12345') len(d) d.popleft() d.pop() d 输出结果: 5 '1' '5' deque(['2', '3', '4']) 我们还可以限制deque的长度: d = deque(maxlen=30) 当限制长度的deque增加超过限制数的项时, 另一边的项会自动删除: d = deque(maxlen=2) d.append(1) d.append(2) d d.append(3) d deque([1, 2], maxlen=2) deque([2, 3], maxlen=2) 添加list中各项到deque中: d = deque([1,2,3,4,5]) d.extendleft([0]) d.extend([6,7,8]) d 输出结果: deque([0, 1, 2, 3, 4, 5, 6, 7, 8]) -
Erratum
Hello everyone.We are sorry but it appears we published a partial post yesterday evening. It has been unpublished and its full version will be re-published tonight.In the mean time, have a great day everyone. -
cached-property: Don't copy/paste code
In Python, the @cached_property decorator is a really nice piece of code. What it does is it caches the result of a property call. The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned. If that doesn't make much sense, below is a snippet of code that shows the code and demonstrates it in action. As always, I'm using pytest to validate my code: from datetime import datetime, timedelta import time class cached_property(object): """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value class SlowClass1(object): @cached_property def very_slow(self): """Represents a performance heavy property.""" time.sleep(1) # Wait a WHOLE second! return "I am slooooow" def test_slow_class1(): # Instantiate the slow class slow_class = SlowClass1() # Start the clock! start = datetime.now() # Call the property. This time it's really slow... assert slow_class.very_slow == "I am slooooow" # Check … -
cached-property: Don't copy/paste code
In Python, the @cached_property decorator is a really nice piece of code. What it does is it caches the result of a property call. The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned. If that doesn't make much sense, below is a snippet of code that shows the code and demonstrates it in action. As always, I'm using pytest to validate my code: from datetime import datetime, timedelta import time class cached_property(object): """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value class SlowClass1(object): @cached_property def very_slow(self): """Represents a performance heavy property.""" time.sleep(1) # Wait a WHOLE second! return "I am slooooow" def test_slow_class1(): # Instantiate the slow class slow_class = SlowClass1() # Start the clock! start = datetime.now() # Call the property. This time it's really slow... assert slow_class.very_slow == "I am slooooow" # Check … -
Creating a custom user model in Django 1.6 - Part 4
Hi everyone and welcome back to this Django tutorial. If you haven't done so yet, make sure to check out the first, second and third part of this tutorial before getting started today.This week we will start by covering the admin login form and allowing users to log into the admin site using their e-mail address instead of their username.Then we will go through a couple more advanced cases of custom user model in Django, including expirable users. -
将 Sublime 3 打造成 Python/Django IDE
Sublime Text 是一款非常强大的文本编辑器, 下面我们介绍如何将 Sublime Text 3 打造成一款 Python/Django 开发利器: 1. 安装 Sublime Text 3 虽然现在的 Sublime 3 还处于 beta 阶段, 但已经非常稳定了, 而且速度比 Sublime 2 得到了增强. Sublime 3 可以到官网下载并安装. Sublime 虽然是免费软件, 但如果有足够的经济能力, 可以考虑购买以表示支持. 2. 安装 Package Control Sublime Package Control 可以说是必须安装的插件, 因为其方便的提供了安装/升级/删除 Sublime 插件的功能, 安装方法见Package Control 官网. 安装完毕后, 就可以使用快捷键 ctrl+shift+p (Win, Linux) 或 cmd+shift+p (OS X), 其中以 Package Control: 开头的都是其相关命令, 最常用的可能就是 Package Control: Install Package, Package Control: Remove Package, Package Control: List Packages 这几个命令了. 3. 推荐安装的插件 现在可以使用 Package Control 安装其他插件了. 使用快捷键 ctrl+shift+p (Win, Linux) 或 cmd+shift+p (OS X), 输入 Package Control: Install Package 回车, 输入 package 名再回车安装: Anaconda Anaconda是目前 Sublime 3 中最好的 Python 自动补全和语法提示插件, 并且提供了"跳转到定义", "查找使用", "显示文档", "自动重命名"等 IDE 中插件的功能. Djaneiro 提供了对Django的支持. SideBarEnhancements 提供了对默认的侧边栏的增强功能. Sublime的侧边栏可以使用快捷键 Ctrl+k Ctrl+b (Linux, Win), CMD+k CMD+b (OS X) 调出来. 安装之后, 还可以通过F12键在浏览器中打开当前文件. Git 相关 我们需要安装 SublimeGit 和 GitGutter, 前者可以帮助我们在 Sublime 中使用 Git 命令 (通过 ctrl+shift+p 或 cmd+shift+p), 后者在编辑时在 Gutter 显示 Git 差异, 十分方便. 主题相关 Theme - Soda 和 Monokai Extended, 安装之后在 user settings 中设置使用: "color_scheme": "Packages/Monokai Extended/Monokai Extended.tmTheme", "theme": "Soda Dark 3.sublime-theme", 其他插件 还可以安装 Emmet, SublimeLinter (注意依赖关系), ColorPicker, Gitignore等插件 4. 设置 以下是推荐的设置, 可以直接复制黏贴放入 user settings 中, 需要注意的是字体文件需要提前安装: { "always_show_minimap_viewport": true, "auto_complete_commit_on_tab": false, "auto_find_in_selection": true, "bold_folder_labels": true, "color_scheme": "Packages/Monokai Extended/Monokai Extended.tmTheme", "theme": "Soda Dark 3.sublime-theme", "default_line_ending": "unix", … -
O'Reilly Deal: 50% Off Lightweight Django
O'Reilly Media, the go-to source for technical books, just let us know that they're having a 50% off sale on eBook pre-orders of Lightweight Django today. Use coupon code: DEAL. -
O'Reilly Deal: 50% Off Lightweight Django
O'Reilly Media, the go-to source for technical books, just let us know that they're having a 50% off sale on eBook pre-orders of Lightweight Django today. Lightweight Django is being written by our very own Technical Director, Mark Lavin and Caktus alumna Julia Elman. We would've thought the book was a fantastic intro to the power of Django in web app development anyway, but since Mark and Julia wrote it, we think it’s extra fantastic. Mark and Julia are continuing to write, but O'Reilly is providing this special pre-release peek for pre-orders. Those that pre-order automatically receive the first three chapters, content as it’s being added, the complete ebook, free lifetime access, multiple file formats, and free updates. -
The End of an Era
Django migrations have come a long way, but it stands on the shoulders of one project that has come just a little bit further. It's been a long while since I posted news of the Django migrations work; my apologies for that, and I'll write about what's been going on there (and the upcoming 1.7 release) soon. For now, though, I want to focus on the past, rather than the future. Today I've released what is probably the last version of South, version 1.0. South has had very few changes for a couple of years now, and the only reason it's getting a release at all is one new feature to aid in the upgrade to Django 1.7. Easier Upgrades This feature is that South will now look first for a south_migrations directory, before falling back to migrations. This one small change means that third-party libraries and apps can support both South and the new-style 1.7 migrations, by moving their legacy South migrations into the south_migrations directory, and having the Django migrations in the migrations directory. This is the end result of the attempt to try and introduce a forwards-compatible "South 2" that would read the new migration format but … -
在 Selenium 中设置不同的浏览器进行 web application 测试
通常我们当我们需要测试JavaScipt, 兼容性或模拟用户行为时, 我们会用使用 Selenium 和 django 的 LiveServerTestCase Class. 默认情况下 Selenium 的 WebDriver 启动的是 Firefox 浏览器, 那么如何使用 Selenium 配合其他浏览器呢? 当然 Selenium 是支持其他浏览器的, 但如果想要使用其他浏览器, 需要要我们做一点不同的设置. 接下来, 我们就演示一下如何设置: 1. Firefox 首先我们演示一下默认情况下如何打开 google.com 并截图: from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.google.com') browser.save_screenshot('screen.png') browser.quit() 2. Chromium 或 Chrome 首先你要安装有 Google Chrome 浏览器. 你还需要chromedriver, 你可以在Chrome Driver官网上下载到 在 Selenium 中使用 Chrome: from selenium import webdriver browser = webdriver.Chrome(executable_path='/usr/lib/chromium-browser/chromedriver') browser.get('http://www.google.com/') browser.save_screenshot('screen_chromium.png') browser.quit() 3. Android 浏览器 在 Android 设备上运行 Selenium 的话, 你必须安装 Selenium server APK, 并启动该APK. 如果是在虚拟机中运行的话, 则需要使用 adb 安装 Selenium server APK: 显示所有 Android 虚拟机: ./adb devices 记下你想要安装的虚拟机ID, 并安装: ./adb -s ID_NUMBER -e install -r android-server-*.apk 再启动该虚拟机. 我们还需要为已经启动的虚拟机设置端口映射, 这是为了让 Selenium 能够与服务器交流: ./adb -s ID_NUMBER forward tcp:8080 tcp:8080 如果使用的是真实的设备, 那我们只需要使用设备的真实IP地址即可: from selenium import webdriver desired_capabilities = webdriver.DesiredCapabilities.ANDROID desired_capabilities['deviceOrientation'] = 'landscape' #portrait browser = webdriver.Remote("http://localhost:8080/wd/hub", desired_capabilities=desired_capabilities) browser.get('http://www.google.com') browser.save_screenshot('screen_android.png') browser.quit() 4. iOS (iPad, iPhone) iOS只能在OSX上使用. 你可以查看ios-driver. 5. 在线 Selenium 服务 如果你想方便的使用 Selenium, 那么也可以尝试 saucelabs.com 或 testingbot.com. 他们提供了在线 Selenium 测试 API. -
Webby stuff
Latest Evennia come with a range of improvements, mainly related to its integration with the web.New and improved ways to expand the website/webclientThanks to the work of contributor Kelketek, Evennia's Django-based web system (website and webclient) has been restructured to be much easier to expand. Previously you had to basically copy the entire web/ folder into your game and modify things in-place. This was not ideal since it made it inherently harder to update when things changed upstream. Now Evennia makes use of Django's collectstatic functionality to allow people to plugin and overload only the media files and templates that they need. Kelketek wrote a new and shiny web tutorial explaining just how things work. Websocket-based webclient with OOBEvennia's webclient was an ajax-based one using a long polling ("comet") paradigm to work. These days all modern browsers support websockets though, a protocol that allows asynchronous server-client communication without the cludgery of long polling. So Evennia's new webclient will now use websockets if the browser supports it and fall back to the old comet client if it does not.The new client also has full support for OOB (Out-of-band) communication. The client uses JSON for straight forward OOB messaging with the server. As part of this, … -
学习Python Django的一些资料
本篇中将列举一些较新的学习python和django的资源. 以下资源主要针对Django 1.6, Python 2.7.x或Python 3.4.x: Python 初学者 Learn Python the Hard Way: http://learnpythonthehardway.org, 如果你不了解Python, 那么这是一个既有免费的HTML资料, 又有付费课程的网站. Django 初学者 Django 官方文档: https://docs.djangoproject.com/en/1.6/, 从django 1.5开始, 官方文档有了非常大的改进和补充, 如果你使用过早期版本的Django, 那么请确保阅读过正确版本的官方文档. Tango with Django: http://www.tangowithdjango.com, 使用django 1.5.4 和大量例子的教程. Test-Driven Web Development Python: http://chimera.labs.oreilly.com/books/1234000000754/, Harry Percieval撰写的, 如何在Django开发过程中使用敏捷/TDD开发的流程, 其HTML资源是免费的! Getting Started with Django: 由Django Software Foundation赞助, 针对django 1.5的免费视频课程, 制作者是Kenneth Love. Django 中高级 Pro Django, 第二版: Pro Django, 一本带你深入了解Django的书. ccbv.co.uk: ccbv.co.uk, 针对Django Class based view提供了详细的method和attribute介绍. GoDjango: http://godjango.com, 一系列关于django的视频教程. Python 其他资料 Python Cookbook 第三版: Python Cookbook, 关于Python 3.3+的书, 其中含有大量优秀的代码. Treading on Python Volume 2: Treading on Python Volume 2: Intermediate Python, 书中包含了许多高级Python结构. Writing Idiomatic Python 3.3: Writing Idiomatic Python 3.3, 书中包含了很多代码优化, 增加可读性的技巧. Writing Idiomatic Python 2.7.3: , 针对python2.7.3. Effective Django: effectivedjango.com, 包含了Nathan Yergler在PyCon 2012, PyOhio 2012, PyCon 2013中的演讲和笔记. JavaScript 资料 Secrets of the JavaScript Ninja: Secrets of the JavaScript Ninja JavaScript: The Definitive Guide: JavaScript: The Definitive Guide JavaScript: The Good Parts: JavaScript: The Good Parts JavaScript Patterns: JavaScript Patterns -
Python语言的一小点优雅表现
本篇中, 我们展示一下一段非常小的代码, 这段代码十分吸引我们, 因为它使用十分优雅和直接的方式解决了一个常见的问题. 比如, 我们希望希望检测"一段string是否以特定的字符串结尾?", 通常我们使用: if needle.endswith('ly') or needle.endswith('ed') or needle.endswith('ing') or needle.endswith('ers'): print('Is valid') else: print('Invalid') 十分丑陋是吧? 如果我们检测变量needle是否是以下特定字符串之一的话, 会这样写: if needle in ('ly', 'ed', 'ing', 'ers'): print('Is valid') else: print('Invalid') 但是, 我们无法在 endswith function 中使用 in, 但我们换一种想法, 我们需要检查的其实是"一段string的结尾是否是以下字符串的任意一个?", 我们会发现python有内部函数any, 于是我们的代码可以改为: if any([needle.endswith(e) for e in ('ly', 'ed', 'ing', 'ers')]): print('Is valid') else: print('Invalid') 相信很多读者在此会不同意我的做法, 或者有更好的写法存在. 但这已经不重要. 我明白你们大多数都会使用类似的写法面对这一相似的问题. 我真正的目的其实是展示一下Python的优雅之处. -
Django 1.6 最佳实践: 如何搜索查找并解决Django相关的问题
每个程序员都会在开发过程中遇到这样或那样的问题, 有时光靠一个人是无法解决所有问题的, 所以我们应该找到适当的地方提问. 1. 卡住是怎么办 按照以下步骤, 前提是你需要懂点英文: 尽可能自己想办法解决 仔细阅读相关文档, 确保不错过任何相关内容 在Google, 百度, mailing lists或StackOverFlow上查看是否有人遇到相同问题 找不到? 在StackOverFlow上问问题, 需要使用小例子说明该问题, 并列出你的开发环境, 使用的软件版本 过了几天都没人回答? 到Django-users mailing list 或 django IRC中再提问 2. 如何问问题 IRC代表Internet Relay Chat, 在Freenode IRC网络中存在#python和#django频道, 其中都是python和django的开发人员. 对于新手而言, 有时你提的问题会被忽略, 有时甚至会被嘲笑, 但请不要感到沮丧, 这是对事不对人的. 这些IRC都是由志愿者维护的, 因此在你提问的同时, 也应当尽量回答别人的问题. 在你提问前, 请先确保你做过功课, 将其作为最后一根救命稻草 将相关的代码放入https://gist.github.com/中 问题尽可能的详细, 并提供联想gist的链接 当别人提供帮助时, 应当感谢别人 我们也应当在社区中变得更积极, 投入越多, 回报也会多. 参与社区的途径: 参加Python和Django会议, 可以通过https://wiki.python.org/moin/LocalUserGroups找到你当地的小组 对开源的Django package贡献代码 参加IRC频道, 并提供帮助 在StackOverFlow上回答问题 订阅planet django博客 等的呢 -
Release 1.1.1
-
Django 1.6 最佳实践: Continuous Integration
Continuous integration (CI) 是一种软件开发实践, 常用于团队间频繁合并工作使用. 每一次合并都要经过自动构建和测试尽快验证其正确性. 许多团队都发现这一方式能大大降低合并中出现的麻烦和, 并增强软件统一性. 以下是一个典型的开发流程: 程序员写代码, 运行本地测试, 将代码推至代码库, 通常最少一天一次 代码库变化触发自动构建工具 自动构建工具运行构建程序. 其间发生任何错误就将本次推送驳回 自动构建工具运行测试程序. 其间发生任何错误就将本次推送驳回 自动构建工具将结果通知开发人员 这一过程有以下优势: 能以最快速度发现bug 便于发现其他问题 每天合并代码的结果导致不会有一次性大规模的改变代码的情况发生 利于对项目的反馈 减轻许多麻烦的事物 1. Continuous Integration 的原则 接下来, 我们讨论一下Continuous Integration的原则: 大量测试 Continuous Integration的前提是构写大量的测试代码. 没有完整的测试就无法做到Continuous Integration. 有些人可能会不同意, 觉得没有测试, 照样可以完成Continuous Integration, 而且也能带给团队同样的优势: 测试开发过程是否成功, 将每个人的代码都同步. 但这一情况是建立在编译语言上的, 因为编译语言在编译时就保障了代码的正确性(不包括其功能性). 保持快速构建 随着开发时间的进行, 测试可能会变得越来越慢, 为此我们提供了一下技巧: 避免使用fixture 没有必要时便面使用TransactionTestCae 避免构写大量setUp()代码 构写小而专一的测试代码 学习数据库优化 2. Continuous Integration 的工具 可以使用以下工具: Tox Tox是一个virtualenv管理和测试用命令行工具, 可以帮助我们使用一个简单的命令对多个Python和Django版本进行测试. 对于不同的数据库, 也应当进行测试. 这是全世界的程序员测试不同版本python兼容性的通用工具. Jenkins Jenkins是一个Continuous Integration的引擎, 也是一个Continuous Integration的标准. 也有许多在线工具继承了Jenkins供我们方便的使用, 有些更是可以方便的集成到类似GitHub, BitBucket等的代码管理库中, 例如Travis-CI, CircleCI和Drone.io. -
Ansible thoughts (plus questions for which I need your input)
Now... how do we structure our servers? How do we put our software on them? How do we configure them? I've done my share of server maintenance and devops and what have you. On linux, that is. Maintaining my own (web)server since 1996 or so. Done a lot with buildout (which means grabbing everything together for a site that has to do with python). Automated much of our installation with Fabric so that $ bin/fab update production was more or less the standard way to update a site. So I know my way around reasonably and I normally keep everything pretty neat and tidy. Now Ansible has come along and several of our sites are managed with that tool. It feels like a much more elaborate version of Fabric. "Elaborate" is meant very positively here. And I want to dive into it and start using it too. Fabric is great for executing commands via ssh on a remote server (including copying files, modifying files etc). Ansible also executes commands via ssh, but comes with a complete system for storing your configuration, handling variables, dividing up the workload into libraries and also for sharing those libraries (called "roles" in ansible-speak). Problem …