Python 异步任务模块 Celery 快速上手 (一)

基本使用

第一步,建立一个celery类的对象,传入一个名称(后续需要这个名称来执行异步任务), 配置消息代理,这里配置了本地redis服务器的第0个数据库

    """
    tasks.py
    """
    from celery import Celery
    celery_app = Celery('name', broker='redis://localhost:6379/0')

那这样就可以通过task装饰器来建立一个简单的异步任务了

    """
    tasks.py
    """
    import time

    @celery_app.task
    def task_name(someone):
        time.sleep(5)
        print('hello {}'.format(someone))

建立好异步任务之后,可以在外部调用这个任务

    from tasks import task_name
    # 任务用过delay方法可以传入参数,方法执行后并不会阻塞后续代码
    task_name.delay('task')
    print('start running!')
    # 也可以不立即执行,可以先用s方法传入参数
    task_name.s('task')
    print('start running!')
    task_name.delay()

对了执行celery命令celery -A name worker, 执行后注册的任务会在console里面输出

数据持久化

想要delay的函数返回的结果就需要在建立celery对象中加入一个backend参数

    """
    tasks.py
    """
    from celery import Celery
    celery_app = Celery('name', broker='redis://localhost:6379/0', backend='redis://localhost:6379/1')

建立一个任务带返回数据功能的

    """
    tasks.py
    """
    import time

    @celery_app.task
    def say_hello(to):
        time.sleep(5)
        return "Hello {}".format(to)

通过ready()方法可以获取任务是否完成,而get()可以获取任务返回结果

    from tasks import say_hello
    import time

    t = say_hello('hello')
    while True:
        r = t.ready()
        if not r:
            print("task done? {}".format(r))
            continue
        print('task done: {}'.format(t.get()))
        break

下一篇详细讲讲Celery的Task类

利用extend自定义jquery函数方法

$.ajax这种jquery方法是不是非常的简短实用,利用extend方法,你也可以给自己定义一个以$符号开头的方法

jQuery.extend( //在jQuery函数下拓展一个方法
    {"hello": function(name) { //方法命名为hello,执行需要传入一个name参数
            console.log("hello " + name)
        }
    }
)
/*
$.hello("world")
output:
hello world
*/

Python基于socket\subprocess编写远程命令执行

简介写socket通讯过程
服务端

1. 初始化socket对象
2. 绑定IP/PORT
3. 监听端口
4. 等待客户链接
    1. 等待消息
    2. 发送消息
5. 关闭客户端链接

客户端

1. 初始化socket对象
2. 链接服务端
    1. 发送消息
    2. 等待消息
3. 关闭与服务器链接

Continue reading Python基于socket\subprocess编写远程命令执行

Python遍历目录查找文件内容

以前要修改wordpress模板上的具体内容时,总是把模板文件夹下载下来,通过sublime text打开文件夹,才能具体的查找到相关内容
当然linux通过grep也可以实现,但还是达不到自己想要的效果
于是用所学的pythoon生成器写了一个小程序
该程序能够查找文件夹下各个文件,并返回关键词所在行号、该行内容、文件所在地址 Continue reading Python遍历目录查找文件内容