如何使函数调用保持在上下文中?

时间:2019-05-21 15:55:10

标签: python flask

我有一个试图使用服务器上定义的name_me方法从服务器调用RPC的类。如果我使用以下命令在iPython中调用它,效果会很好:

jsonrpcclient.request ('http://localhost:5000', 'name_me', N=6).data.result

但是当我尝试用我的班级构建它时,出现错误:

RuntimeError: Working outside of request context.

这通常意味着您尝试使用所需的功能 活动的HTTP请求。查阅有关测试的文档 有关如何避免此问题的信息。

我将客户代码放在代码部分。

class LyricCaller:

    def __update_host_port (self, new_port):
        self.__port = new_port

    def __update_host_address (self, new_address):
        self.__address = new_address

    def __target (self):
        return '{}:{}'.format (self.__address, self.__port)

    def __init__(self, host_address = 'http://localhost:5000', host_port = 5000):
        self.lyric = []
        self.__Lyr_fn = 'name_me'
        self.__update_host_address (host_address)
        self.__update_host_port (host_port)

    def __parse_choice (self, choice):
        return abs (choice)


    def sing(self):
        print (self.lyric)

    def fetch_lyric (self, choice):
        C = self.__parse_choice (choice)
        K = request (self.__target(), self.Lyr_fn, N=1)

我希望有一个返回的字符串,当我直接调用该字符串时可以使用 jsonrpcclient.request('http://localhost:5000','name_me',N = 6).data.result,

但是我仍然收到上下文错误。我尝试过重新启动服务器,但是仍然发生相同的事情。

供进一步参考,下面是服务器代码:

'''

from flask import Flask, request, Response
from jsonrpcserver import method, dispatch

LServer = Flask(__name__)

@method
def name_me (N = 1):
    K = ['How do we sleep while our beds are burning?',
         'You label me, I label you, and so I dub thee Unforgiven', 
         'Carry on my wayward son!',
         'Not dead which eternal lie, stranger aeons death may die',
         'Let the bodies hit the floor', 
         'Wollt ihr das bed in flammen siehen']

    #N = 4
    if N <= len (K):
        O = K[N-1] 
    else:
        import random
        n = random.randint (0, len(K)-1)
        O = K[n]

    return O

@LServer.route ('/', methods = ['POST'])
def index():
    #with LServer.test_request_context():
        req = request.get_data().decode()
        response = dispatch(req)
        return Response (str(response), response.http_status, mimetype="application/json")

if __name__ == '__main__':
    LServer.run()

'''

1 个答案:

答案 0 :(得分:0)

烧瓶documentation说: 如果您在代码中与测试无关的其他地方看到该错误,则很可能表明您应该将该代码移至视图函数中。

因此您的代码将与此类似:

Set @año = Year(Getdate())
Set @mes = Month(Getdate())
Set @m = 1

While @año > 2014 begin
    While @m < 13 begin
        Select @año as año, @m as mes
        set @m = @m + 1
    End
    Set @año = @año - 1
    Set @m = 1
End