Django tricks

关于 session

django.contrib.sessions.middleware | Django documentation | Django

session 是使用 cookie 来进行判断的,通过 session_cookie_name 来提取,然后通过 SessionStore() 来保存。

因此,Django 也是通过 sessionid 来区分用户;(或者其他什么名称)。

使用 cache 作为全局变量

cache.set(‘foo’, ‘bar’) # another function cache.get(‘foo’) # get ‘bar’

使用 cache , django-redis 是一个好方法。可以在使用 cache.lock变量,在应用层面加锁,来完成异步操作,还可以支持分布式应用,十分方便。

django 

# Python文件操作

Python的文件操作很多,为了方便以后查询使用,在此做下记录。

注:这些函数都可以在官网查询,这里做个cache。

[阅读全文]

Python拆包的好处

内容

在最近的一期 realpython 中,我阅读到了这样一段代码:

# Why Python Is Great:
# Function argument unpacking
def myfunc(x, y, z):
    print(x, y, z)
tuple_vec = (1, , 1)
dict_vec = {'x': 1, 'y': , 'z': 1}
>>> myfunc(*tuple_vec)
1, , 1
>>> myfunc(**dict_vec)
1, , 1

之前因为:

  1. 这个东西不是很直观
  2. 这个可能造成参数混乱

而不是很在意这段代码。现在想来,真是很方便的一个东西:我们可以通过这个特性,轻松的拆解response.json这个dict,从而直接使用参数。

注意一点,如果一个函数的参数超过三个,说明你需要拆解这个函数,而不是被参数的数量搞得焦头烂额。

具体例子

这个方法可以方便很多事情,比如说,我可以这样来重新构建输出的变量,而不是一个个print

def add_parameters(params, **kwargs):
    """add kwargs to dict
    Args:
        params: the dict need to add
        kwargs: variable
    """
    params.update(kwargs)
params = {}
add_parameters(params,
                   x_train=x_train.shape,
                   y_train=y_train.shape,
                   x_test=x_test.shape,
                   y_test=y_test.shape)
pretty(params)

vscode为django添加合适的pylint

使用vscode进行django开发的时候,总会出现一些错误,比如说对Django的一些结构进行错误的报错;

这个时候可以安装pylint-django这个插件。

安装方法:pip install pylint-django

使用:

.vscode/配置文件中增加:

    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django"
    ],

即可。

参考

https://stackoverflow.com/questions/45135263/class-has-no-objects-member

python如何使用不可变量const

# python2
# Put in const.py...:
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):
            raise self.ConstError, "Can't rebind const(%s)"%name
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()
# that's all -- now any client-code can
import const
# and bind an attribute ONCE:
const.magic = 23
# but NOT re-bind it:
const.magic = 88      # raises const.ConstError
# you may also want to add the obvious __delattr__

# python3 version
class _const:
    class ConstError(TypeError):
        pass
    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError("Can't rebind const(%s)" % name)
        self.__dict__[name] = value
import sys
sys.modules[__name__] = _const()

这样一来,就可以在python中使用不可变量了。其中,利用魔术方法__setattr__,把一个变量当作是const类的属性,然后使用__dict__来判断当前变量是否已经存在。

通过这个技巧我们还能构造出一系列有意思的东西——

运行截图

refer

pipenv入门指南

前言

pipenv是书写flask的大神kennethreitz的新作;pipenv集成了virtualenv和pip等工具,让你从requirements.pip以及virtualenv的环境中解放出来。并且他还集成了pyenv的选择python版本,可以说是所向披靡了。

这是他的原话:

You no longer need to use pip and virtualenv separately. They work together.
Managing a requirements.txt file can be problematic, so Pipenv uses the upcoming Pipfile and Pipfile.lock instead, which is superior for basic use cases.
Hashes are used everywhere, always. Security. Automatically expose security vulnerabilities.
Give you insight into your dependency graph (e.g. $ pipenv graph).
Streamline development workflow by loading .env files.

相信随着pipenv更加流行,许多工具也会在自己的环境中对pipenv提供支持,解决许多令人不舒服的问题,也能更好的提高编辑的舒适度。

安装pipenv

$ pip install pipenv

创建虚拟环境 virtualenv

  1. 当不存在一个虚拟环境的时候,pipenv将会自动创建一个环境
  2. 你也可以手动创建虚拟环境:
    1. $ pipenv --three 创建Python3虚拟环境
    2. $ pipenv --two 创建Python2虚拟环境
  3. 其他的东西和virtualenv是一样的。

安装包

比如你要使用requests(是的也是这个大神写的)。

[阅读全文]

Python-Tips

来自分布在各处的开发tips

使用nametuple

nametuple用来构建只有少数属性但是没有方法的对象,比如数据库条目。

[阅读全文]

Python在Ubuntu中使用形式

Python在Ubuntu中的形式十分杂乱。对于Debian已经很久没有使用过了,因此不太清楚Debian对于Python的版本是如何管理的。

但是在CentOS中,Python的管理方式是,默认不安装Python3。(CentOS6.5)这对于系统的纯洁性具有相当的保护性。

行文至此,不得不想到,肯定有对于此类讲解的书籍,也会说的比我更加明确。对于此问题,如果我继续深入的读读书,谈一谈,可能会更好。

Debian系的Ubuntu顺承了上游的想法同时包含两个东西,但是我认为,这并不是一个正确的做法。因为总有程序员写代码的时候不喜欢使用env python2。这也就解释了为什么我们仅仅修改了python的指向,但是依然容易出问题。

https://www.zhihu.com/question/21653286

知乎上有许多pip3这种答案,但是这其实是有问题的。尤其是当存在缓存的时候,如果pip2pip3同时安装一个包的时候,pip3或者pip2会读取另一方的缓存,导致安装失败。然后陆续出现问题。这是我所遇到的, 尽管不一定100%发生,但是如果发生了,就对行云流水的体验造成了很大的影响——我不得不去G搜看看问题所在。

所以,最终的解决方案?

http://www.ituring.com.cn/article/261302

以后Linux相关书籍以及想法就写在图灵社区,最终成书,对于大学程序员起指导作用。

Python-建立最简单的web服务器

本文出自svtter.github.io

有三个服务模块可以使用:

  • BaseHTTPServer 最基础web服务.
  • SimpleHTTPServer 可以处理GET和HEAD.
  • CGIHTTPServer 可以处理POST请求和执行CGI.

只需要一行代码即可:

python -m SimpleHTTPServer 8080

如果8080端口被占用,可以选择别的端口来使用.

此处的 SimpleHTTPServer 可以使用以上三个服务模块替代