New Usage of typing module in python

我原本想要分析一下 django webpack;但是写了一半,为了资料论述严谨,又不得不学习了 django component;在 django component 中,又发现了自己之前不知道的一些机制。无奈,先聊聊遇到的 typing 问题吧!

[阅读全文]

Django and Webpack

Webpack is a modern development method for frontend projects. Django is a common backend development framework for Python developers.

I believe that developing with Webpack can make Django development faster.

[阅读全文]

Django 写个过滤器 filter

用 Django 快速开发一个项目,发现 Django 的模板本身不带有整除功能,因此自己手写一个。

├── templates
│   ├── app
│   └── base
├── templatetags
│   ├── app_extras.py
│   ├── __init__.py
│   └── __pycache__
├── tests.py
├── urls.py
├── utils.py
└── views.py

这是目录结构。在 urls.py 添加 app 的名称,例如 app_name = ‘app’ ,然后在与models.py 同级的目录下,新建一个 python 包, templatetags 的,新建自己需要的包名即可。

app_extra.py:

from django import template

register = template.Library()


def mod(value):
    return value % 11


register.filter('mod', mod)

这里因为需求比较简单,因此直接就赋值了 11.

应用到模板中:

{% load app_extra %}

{% for image in image_list %}
	{% if forloop.counter|mod == 0 %}
		<h3>检查点</h3>
	{% endif %}
{% endfor %}

随后即可看到结果。

[阅读全文]

Python functools

Python functools包中,有个很好的函数叫做partial ,中文直接翻译为片函数,此前一直都没有使用过。最近通过阅读别人的代码,学会了这一技能,着实好用。

使用partial,可以把一些固有功能代码做一个整合;

比如我希望一个函数专门做 int2 转换

int2 = partial(int, base=2)

甚至还可以再过分一点,把 base 变成一个字典量传入。

多使用内建函数 locals,可以极大的减少自己的代码量;

这不得不让我感概:真正的 Pythonista,永无止境。

def in_func():
	a = 2
	b = 3

	def test(a, b, **args):
		return a + b

	print(test(**locals()))

CHANGELOG

date content
20230829 调整了一些语病
python 

Django导出博客为hexo博客

Django导出主要使用render_to_string方法来进行;

可以参考的源码如下:

from article.models import Article
from django.template.loader import render_to_string
posts = Article.objects.all()
for post in posts:
    title = post.title
    title = title.replace('[', '')
    title = title.replace(']', '')
    context = {
        'title': title,
        'cre_date': post.cre_date,
        'updated': post.up_date,
        'content': post.content,
        'category': post.category.name,
        'tag': post.tag
    }
    content = render_to_string('article.html', context)
    filename = 'export/' + post.title + '.md'
    with open(filename, 'w') as f:
        f.write(content)

对应的渲染article.html

title: {{ title }}
date: 2018-01-05T01:00:00+08:00
updated: {{ updated | date:"Y/m/d H:i:s" }}
tags: [
{% for tag in tags %}
    '{{ tag.name }}',
{% endfor %}
]
categories: [
    '{{ category }}',
]
---
{{ content | safe }}

运行的时候,python manage.py shell,然后导入export 包即可。