简体   繁体   English

如何在使用多处理的无限循环中编程时发出请求

[英]How to make requests while program in infinite loop with multiprocessing

I have two function which are require to run same time.我有两个需要同时运行的函数。 read_card needs to run in an infinite loop and waits for new cards(it is actually a Nrf reader) and adds some string to a queue , send_data suppose to get values from queue and send them to the server via requests library.Everything works when I do not use multiprocessing. read_card需要在无限循环中运行并等待新卡(它实际上是一个 Nrf 读取器)并将一些字符串添加到队列中, send_data假设从队列中获取值并通过请求库将它们发送到服务器。当我一切正常时不要使用多处理。 But I need concurrency I guess.但我想我需要并发。

Here is my two function.这是我的两个功能。

def read_card(reader, configs):
    print("First started")
    while True:
        authorized_uid = reader.is_granted(reader.read())
        print("Waiting for card")
        #TODO:If not authorized in AccessList.txt look to the server
        if authorized_uid is not None:
            print(authorized_uid)
            open_door()
            check_model = CheckModel(configs.DeviceSerialNumber, authorized_uid)
            message_helper.put_message(check_model)

def send_data(sender):
    print("Second started")
    while True:
        message_model = message_helper.get_message()
        if message_model is not None:
            sender.send_message(message_model)

Here is how I call main这是我调用 main 的方式

def main():
    download_settings()
    create_folders()
    settings = read_settings()
    accessList = get_user_list(settings)
    configure_scheduler(settings)  

    message_sender = MessageSender(client.check,client.bulk)

    reader_process = multiprocessing.Process(name = "reader_loop", target = read_card, args=(Reader(accessList, entryLogger),configs,))
    message_process = multiprocessing.Process(name = "message_loop", target = send_data, args=(message_sender,))
    reader_process.start()
    message_process.start()

if __name__ == '__main__':
    main()

And those are for debugging.那些用于调试。 I printed what put_message and send_message from different classes.我打印了来自不同类的put_messagesend_message

def send_message(self,model):
    print(model)
    return self.checkClient.check(model)

def put_message(self, message):
    print(message)
    self.put_to_queue(self.queue, message)
    self.put_to_db(message)

I expect to see some object names in terminal, but I only see below.我希望在终端中看到一些对象名称,但我只能在下面看到。 Also reader does not work.阅读器也不起作用。

 First started Second started

Which part I do wrong?我做错了哪一部分?

Use a Queue to communicate between processes.使用Queue在进程之间进行通信。 Then when you read a card inside reader create a new job and push it into the queue, then pop this job inside the processor and send the request.然后,当您在reader读取卡片时,创建一个新作业并将其推入队列,然后在处理器内弹出此作业并发送请求。

Here's a proof of concept:这是一个概念证明:

from datetime import datetime
from multiprocessing import Process, Queue
from random import random
from time import sleep

import requests


def reader(q: Queue):
    while True:
        # create a job
        job = {'date': datetime.now().isoformat(), 'number': random()}
        q.put(job)
        # use a proper logger instead of printing,
        # otherwise you'll get mangled output!
        print('Enqueued new job', job)
        sleep(5)


def client(q: Queue):
    while True:
        # wait for a new job
        job = q.get()
        res = requests.post(url='https://httpbin.org/post',
                            data=job)
        res.raise_for_status()
        json = res.json()
        print(json['form'])


if __name__ == '__main__':
    q = Queue()
    reader_proc = Process(name='reader', target=reader, args=(q,))
    client_proc = Process(name='client', target=client, args=(q,))

    procs = [reader_proc, client_proc]
    for p in procs:
        print(f'{p.name} started')
        p.start()
    for p in procs:
        p.join()

which prints:打印:

reader started
client started
Enqueued new job {'date': '2019-07-01T15:51:53.100395', 'number': 0.7659293922700549}
{'date': '2019-07-01T15:51:53.100395', 'number': '0.7659293922700549'}
Enqueued new job {'date': '2019-07-01T15:51:58.116020', 'number': 0.14306347124900576}
{'date': '2019-07-01T15:51:58.116020', 'number': '0.14306347124900576'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM