[英]Python and multiprocessing… how to call a function in the main process?
[英]Python Multiprocessing (Flask) - Calling a function from main process
這是我的代碼:
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
.
這似乎給我一個錯誤說
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.
無論如何我可以解決這個問題?
更新
另外,我嘗試像這樣在 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()
這只會給我帶來另一個錯誤。
如果您只需要讀取此 cookie,則可以將其作為參數發送
p = Process(target=worker, args=(processValues, getCookie()))
或直接
p = Process(target=worker, args=(processValues, request.cookies.get('username'))
但是你必須在工人中得到它
def worker(state, username):
類似的方式你可以嘗試發送完整的request
p = Process(target=worker, args=(processValues, request))
順便說一句:據我所知, multiprocessing
使用pickle
將 arguments 作為文件發送。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.