简体   繁体   English

Python 多处理(Flask) - 从主进程调用 function

[英]Python Multiprocessing (Flask) - Calling a function from main process

This is my code:这是我的代码:

from flask import Flask, render_template, url_for, redirect, request, flash, Markup, make_response, Response
from multiprocessing import Process, Value

def getCookie():
    return request.cookies.get('username')

def worker(state):
    if state.value == 1:
        while True:
            print(getCookie())

if __name__ == '__main__':
    processValues = Value('i', 1)
    p = Process(target=worker, args=(processValues, ))
    p.start()
    app.run()
    p.join()

So worker is the function started by Multiprocessing and it's trying to call function getCookie() which uses a function by Flask . So worker is the function started by Multiprocessing and it's trying to call function getCookie() which uses a function by Flask .

It seems to throw me an error saying这似乎给我一个错误说

RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

Anyway I can fix this?无论如何我可以解决这个问题?

UPDATE更新

Also, Ive tried sending the request function in the args like so另外,我尝试像这样在 args 中发送请求 function

from flask import Flask, render_template, url_for, redirect, request, flash, Markup, make_response, Response
from multiprocessing import Process, Value

def worker(state, req):
    if state.value == 1:
        while True:
            print(req.cookies.get('username'))

if __name__ == '__main__':
    processValues = Value('i', 1)
    p = Process(target=worker, args=(processValues, request ))
    p.start()
    app.run()
    p.join()

And this just throws me another error.这只会给我带来另一个错误。

if you need to only read this cookie then you could send it as argument如果您只需要读取此 cookie,则可以将其作为参数发送

p = Process(target=worker, args=(processValues, getCookie()))

or directly或直接

p = Process(target=worker, args=(processValues, request.cookies.get('username'))

But you have to get it in worker as但是你必须在工人中得到它

def worker(state, username):

Similar way you could try to send full request类似的方式你可以尝试发送完整的request

p = Process(target=worker, args=(processValues, request))

BTW: as I know multiprocessing uses pickle to send arguments as file.顺便说一句:据我所知, multiprocessing使用pickle将 arguments 作为文件发送。

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

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