34篇 python related articles

python中的*args 和 **kwargs

*args**kwargs 均为可变参数,方便记忆可以理解为 *args是列表形式的多个参数,不过它传值不是以list, 就是func(arg1, arg2, arg3...)
**kwargs可以理解为字典形式的多组key, value键值对,不过它传值也不是字典,而是func(a=1, b=2, c=3...)。

它们同时出现在func的定义中时,*args在前, **kwargs在后

**kwargs通常用在类的初始化多个配置项参数值传递。举一个pymongo的例子:

class MongoClient(common.BaseObject):
    def __init__(
            self,
            host=None,
            port=None,
            document_class=dict,
            tz_aware=None,
            connect=None,
            type_registry=None,
            **kwargs):
More ~

python面试官问你用过列表推导式吗

推导式?什么东西?我还真头一回听说这名词,以为是链表、二叉树之类的问题,面试官这样问,只能摇头不解。

回来查下推导式,原来就是常用的list的for in for,有点想笑,这么简单的列表创建问题问得让我摸不着头脑,有些术语听起来很深奥,其实就是常用的表达式,这好比你去问别人设计模式,你用过什么设计模式,什么工是工厂模式?什么是单例模式等等,虽然对术语可能一知半解或者解释不清,其实就是常常在用的。

newlist = [i for i in range(1, 100) if i%3==0]
More ~

[python] 使用密码连接redis服务器 Connect redis with password

第一种方法:

rds = redis.StrictRedis(host='localhost', port=6379, password='123456')

第二种方法:

redis_config = {
        'host': os.getenv('REDIS_HOST', '127.0.0.1'),
        'port': os.getenv('REDIS_PORT', 6379),
        'password': os.getenv('REDIS_PWD', '123456')
    }
redis_uri = 'redis://:{password}@{host}:{port}/0'.format(**redis_config)
redis = Redis.from_url(redis_uri)
More ~

Django root url point to app root

In the Django's tutorial, I created an app name front, and its urls.py definition like this:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('front/', include('front.urls')),
    path('admin/', admin.site.urls),
]

So, if the app's url in web browser is http://127.0.0.1:8000/front/
In fact, most website the home page won't have subdirectory. So, the solutions is here:

from django.contrib import admin
from django.urls import path, include, re_path

urlpatterns = [
    re_path(r'^', include('front.urls')),
    path('front/', include('front.urls')),
    path('admin/', admin.site.urls),
]

Now, you can visit the app root url in the home page. http://127.0.0.1:8000/

More ~

Regex url route in Flask

class RegexConverter(BaseConverter):
    def __init__(self, map, *args):
        BaseConverter.__init__(self, map)
        self.map = map
        self.regex = args[0]


app.url_map.converters['regex'] = RegexConverter

Define a regex route

@app.route('/go/<regex("[a-zA-Z0-9]+"):url>')
def go(url):
    real_url = redis.get(url)
    return redirect(real_url)

More ~

Dockerfile指定pip安装源

Dockerfile使用的python3.7作为基础镜像 FROM python:3.7,但是执行
RUN pip install --no-cache-dir -r requirements.txt
是默认走了这个源,https://files.pythonhosted.org/packages,编译用时太久。

无赖修改成国内源来加快编译速度:
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --no-cache-dir -r requirements.txt

附国内其它源:
阿里云 http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

More ~

Could not fetch URL https://pypi.python.org/simple/pyecharts/

用virtual env后 pip安装一些个库可能会报这个

Could not fetch URL https://pypi.python.org/simple/*/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) - skipping

原因在于pip版本过低了,我的python2.7 用env后就是8.0,可以用下面的方法更新再重试pip install

curl https://bootstrap.pypa.io/get-pip.py | python

More ~