Define global function using in jinja templates

原文是Call a python function from jinja2, 原文中点赞数量最高的并不是完美的答案,我采用的下面的方案。

Variables can easily be created:

def example():
    return dict(myexample='This is an example')

The above can be used in a Jinja2 template with Flask like so:

{{ myexample }}

(Which outputs This is an example)

As well as full fledged functions:

def utility_processor():
    def format_price(amount, currency=u'€'):
        return u'{0:.2f}{1}'.format(amount, currency)
    return dict(format_price=format_price)

The above when used like so:

{{ format_price(0.33) }}

(Which outputs the input price with the currency symbol)

Alternatively, you can use jinja filters, baked into Flask. E.g. using decorators:

def reverse_filter(s):
    return s[::-1]

Or, without decorators, and manually registering the function:

def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter

Filters applied with the above two methods can be used like this:

{% for x in mylist | reverse %}
{% endfor %}
阅读全文 ~

Python: 使用requests下载图片

You can either use the response.raw file object, or iterate over the response.

To use the response.raw file-like object will not, by default, decode compressed responses (with GZIP or deflate). You can force it to decompress for you anyway by setting the decode_content attribute to True (requests sets it to False to control decoding itself). You can then use shutil.copyfileobj() to have Python stream the data to a file object:

import requests
import shutil

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)       

To iterate over the response use a loop; iterating like this ensures that data is decompressed by this stage:

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r:

This'll read the data in 128 byte chunks; if you feel another chunk size works better, use the Response.iter_content() method with a custom chunk size:

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        for chunk in r.iter_content(1024):

Note that you need to open the destination file in binary mode to ensure python doesn't try and translate newlines for you. We also set stream=True so that requests doesn't download the whole image into memory first.

阅读全文 ~

mkdir -p functionality in Python


import errno    
import os

def mkdir_p(path):
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):

阅读全文 ~

MongoDB: Query fields if not exists

Existence Check

The { item : { $exists: false } } query matches documents that do not contain the item field:

db.inventory.find( { item : { $exists: false } } )

Studio3T里的Query查询条件可以是 {downloaded:{$exists: false}} 即可以查出那些没有这个downloaded字段的数据

阅读全文 ~

Python 魔术方法备忘

魔术方法 调用方式 解释
new(cls [,...]) instance = MyClass(arg1, arg2) new 在创建实例的时候被调用
init(self [,...]) instance = MyClass(arg1, arg2) init 在创建实例的时候被调用
cmp(self, other) self == other, self > other, 等。 在比较的时候调用
pos(self) +self 一元加运算符
neg(self) -self 一元减运算符
invert(self) ~self 取反运算符
index(self) x[self] 对象被作为索引使用的时候
nonzero(self) bool(self) 对象的布尔值
getattr(self, name) # name 不存在 访问一个不存在的属性时
setattr(self, name, val) = val 对一个属性赋值时
delattr(self, name) del 删除一个属性时
__getattribute(self, name) 访问任何属性时
getitem(self, key) self[key] 使用索引访问元素时
setitem(self, key, val) self[key] = val 对某个索引值赋值时
delitem(self, key) del self[key] 删除某个索引值时
iter(self) for x in self 迭代时
contains(self, value) value in self, value not in self 使用 in 操作测试关系时
concat(self, value) self + other 连接两个对象时
call(self [,...]) self(args) “调用”对象时
enter(self) with self as x: with 语句环境管理
exit(self, exc, val, trace) with self as x: with 语句环境管理
getstate(self) pickle.dump(pkl_file, self) 序列化
setstate(self) data = pickle.load(pkl_file) 序列化
阅读全文 ~



  • 腾讯云的免费证书
    Screen Shot 2018-05-29 at 23.29.17.png


阅读全文 ~