核心代码
def autoSlug(str):
translate_url = ‘http://translate.google.com/translate_a/t?client=t&text=%s&hl=en&sl=zh-CN&tl=en&pc=0′%str.replace(‘ ‘,‘-‘).encode(“utf-8”)
translate_result = urlfetch.fetch(translate_url,None,urlfetch.GET,HEADERS)
if translate_result.status_code == 200:
trans_reg = u'”trans”:”([^”]*)”‘
translate_content = re.findall(trans_reg, translate_result.content)[0]
translate_url = ‘http://translate.google.com/translate_a/t?client=t&text=%s&hl=en&sl=zh-CN&tl=en&pc=0′%str.replace(‘ ‘,‘-‘).encode(“utf-8”)
translate_result = urlfetch.fetch(translate_url,None,urlfetch.GET,HEADERS)
if translate_result.status_code == 200:
trans_reg = u'”trans”:”([^”]*)”‘
translate_content = re.findall(trans_reg, translate_result.content)[0]
translate_content = translate_content
.replace(‘ ‘,‘-‘)
.replace(‘\‘,‘-‘)
translate_content = re.sub(u'[^a-zA-Zd_]’,‘-‘, translate_content)
logging.info(“*********”+translate_content)
return translate_content
效果可以看我每篇文章的url,懒人必备,呵呵
补充. 上述代码需插入admin.py,并修改admin_entry类的entry.slug=entry_slug.replace(” “,”-“)为entry.slug=autoSlug(title) 即可。 但这样做会增加提交文章时额外的时间. 在GAE找个不稳定的环境下,及容易崩溃.因此可以用下面方法代替上述方法.
- 找到micolog/views/admin/entry.html页面.
- 找到大概288行,有段<input type=”text” value=”{{entry.slug|escape}}” tabindex=”1″ size=”30″ name=”slug”/></br>.在</br>换行标记前插入<input id=”auto_translate” type=”button” value=”auto”>标签.
- 然后回滚到该页面最上面,随便找一行空白,加入下面代码
JavaScript语言: 临时自用代码
<script type=“text/javascript” src=“http://www.google.com/jsapi”></script>
<script type=“text/javascript”>
google.load(“language”, “1”);
$(function(){
$(‘#auto_translate’).click(function(){
var title = $(“#title”).val();
if(title!=“”){
google.language.translate(title,“zh-CN”,“en”,function(result) {
res = result.translation.replace(/s{1,}/g,‘-‘);
$(“input[name=’slug’][type=’text’]”).val(res);
});
<script type=“text/javascript”>
google.load(“language”, “1”);
$(function(){
$(‘#auto_translate’).click(function(){
var title = $(“#title”).val();
if(title!=“”){
google.language.translate(title,“zh-CN”,“en”,function(result) {
res = result.translation.replace(/s{1,}/g,‘-‘);
$(“input[name=’slug’][type=’text’]”).val(res);
});
}else{
alert(‘请先输入标题!’);
}
});
});
</script>
最终效果如图,
近期评论