0

I am new to Python and want to build an application that can accept a certain number of HTTP requests, then go on to parse these requests and process the data stored in the body.

I have found a lot of tutorials for REST APIs and ways to create servers that will indefinitely accept incoming requests, however, it does not seem like good practice to me to start such a server then force stop it after a short amount of time. In addition, I need to compare data within request bodies to determine when to stop accepting requests, and I had trouble storing data between request handler calls using Flask.

My question is this:

What is a good practice for accepting HTTP requests in Python, where the amount of requests to be received depends on the data in each request body (such that when this requirement is met, the program can stop accepting connections and go on to process the stored request data)

kshah
  • 1,667
  • 2
  • 16
  • 24
  • 1
    You need something outside of Flask to store data between requests, like a database. The tutorial covers one way to do this: http://flask.pocoo.org/docs/0.12/tutorial/ – jonrsharpe Aug 18 '17 at 07:34

2 Answers2

0

try this use flask.g to store your request counter, http://flask.pocoo.org/docs/0.10/api/#flask.g

if the counter reach a upper limit , then shutdown flask How to stop flask application without using ctrl-c

sorry, I misunderstand, flask.g is like ThreadLocal in java, different between requests. In this situation, I think the simple way is to use a module variable

access_count = 0
def counter(func):
    def other_func(*args, **kwargs):
        global access_count
        access_count = access_count + 1
        return func(*args, **kwargs)
    return other_func

@counter
@app.route("/aaa")
def a():
    print "aa"
@counter
@app.route("/bbb")
def b():
    print "bb"

def main():
    a()
    b()
    print access_count
xiaoming
  • 1,069
  • 8
  • 10
  • To my understanding, flask.g only persists data between a single request (to ensure the server is kept stateless). I need to be able to persist a variable over multiple calls to the request handler function – kshah Aug 18 '17 at 17:29
0

If you want to store your data you can use AJAX Request to do it (same problems here)

For stoping the server after a certain number of HTTP requests, you need one counter and you use flask function to shutdown the server manually (flask function to shutdown server)

Hope it's helpful !

Peace

SD3L
  • 171
  • 7