分类标签归档:python

python celery 实现异步任务处理


# 安装celery

pip install celery
pip install eventlet
# eventlet - 具有WSGI支持的异步框架
# eventlet是python库函数,一个是处理和网络相关的,另一个可以通过协程实现并发
# 可以实现'并发'(绿色线程),非阻塞
# 对Python库函数改写,支持协程

#安装broker

可以选择RabbitMQ或者Redis,celery官方推荐的是用rabbitmq,不过我这里,两种broker 我都会安装

  • redis 安装
# 下载编译
wget http://download.redis.io/rele

Read more

python 分布式进程


参考廖雪峰的官方网站 https://www.liaoxuefeng.com/wiki/1016959663602400/1017631559645600

Python的multiprocessing模块不但支持多进程,其中managers子模块还支持把多进程分布到多台机器上

如果我们已经有一个通过Queue通信的多进程程序在同一台机器上运行,现在,由于处理任务的进程任务繁重,希望把发送任务的进程和处理任务的进程分布到两台机器上。怎么用分布式进程实现?

原有的Queue可以继续使用,但是,通过managers模块把Queue通过网络暴露出去,就可以让其他机器的进程访问Queue了

# task

Read more

进程 vs 线程


我们介绍了多进程和多线程,这是实现多任务最常用的两种方式。现在,我们来讨论一下这两种方式的优缺点。

首先,要实现多任务,通常我们会设计Master-Worker模式,Master负责分配任务,Worker负责执行任务,因此,多任务环境下,通常是一个Master,多个Worker。

如果用多进程实现Master-Worker,主进程就是Master,其他进程就是Worker。

如果用多线程实现Master-Worker,主线程就是Master,其他线程就是Worker。

多进程模式最大的优点就是稳定性高,因为一个子进程崩溃了,不会影响主进程和其他子进程。(当然主进程挂了所有进程就全挂了,但是Ma

Read more

python ThreadLocal


参考廖雪峰的官方网站 https://www.liaoxuefeng.com/wiki/1016959663602400/1017630786314240

import threading

# 创建全局ThreadLocal对象:
local_school = threading.local()

def process_student():
    # 获取当前线程关联的student:
    std = local_school.student
    print('Hello, %s (in %s)' % (std, threading.current_thread(

Read more

python 多线程


参考廖雪峰的博客https://www.liaoxuefeng.com/wiki/1016959663602400/1017629247922688

import time, threading

# 假定这是你的银行存款:
balance = 0

lock = threading.Lock()

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(10

Read more

python 多进程


可以参考廖雪峰的博客 https://www.liaoxuefeng.com/wiki/1016959663602400/1017628290184064

我自己在树莓派开发的例子

from django.shortcuts import HttpResponse
from common.pygpio import led, sound
from multiprocessing import Process


# Create your views here.
def robot(request):
    """ionum: int gpio的引脚,17表示红

Read more

django rest framework


1.安装

pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support
  • 修改settings 文件的INSTALLED_APPS
INSTALLED_APPS = [
    ...
    'rest_framework',
]
  • 添加路由
    urlpatterns = [
      ...
      url(r'^api-auth/',

Read more