Object Oriented Python with Flask Server?

后端 未结 5 1890
悲哀的现实
悲哀的现实 2021-02-04 02:18

I\'m using Flask to expose some data-crunching code as a web service. I\'d like to have some class variables that my Flask functions can access.

Let me walk you through

5条回答
  •  后悔当初
    2021-02-04 02:55

    if you wish to approach MyServer class as a resource
    I believe that flask_restful can help you:

    from flask import Flask
    from flask_restful import Resource, Api
    import json
    import numpy as np
    
    app = Flask(__name__)
    api = Api(app)
    
    class MyServer(Resource):
        def __init__(self):
            self.globalData = json.load(filename)
    
        def get(self):
            return np.random.choice(self.globalData)
    
    api.add_resource(MyServer, '/')
    
    if __name__ == '__main__':
        app.run()
    

提交回复
热议问题